]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/pluralsight.py
[extractor] Add `_perform_login` function (#2943)
[yt-dlp.git] / yt_dlp / extractor / pluralsight.py
CommitLineData
483fc223
S
1from __future__ import unicode_literals
2
8c3e35dd 3import collections
483fc223 4import json
8c3e35dd 5import os
38eb2968 6import random
21c1a00d 7import re
483fc223
S
8
9from .common import InfoExtractor
10from ..compat import (
11 compat_str,
483fc223
S
12 compat_urlparse,
13)
14from ..utils import (
425f3fdf 15 dict_get,
483fc223 16 ExtractorError,
8c3e35dd 17 float_or_none,
483fc223
S
18 int_or_none,
19 parse_duration,
4dfbf869 20 parse_qs,
756926ff 21 qualities,
8c3e35dd 22 srt_subtitles_timecode,
93d0583e 23 try_get,
3d7e3aaa 24 update_url_query,
6e6bc8da 25 urlencode_postdata,
483fc223
S
26)
27
28
563772ed 29class PluralsightBaseIE(InfoExtractor):
9df6b03c 30 _API_BASE = 'https://app.pluralsight.com'
563772ed 31
836ef484
S
32 _GRAPHQL_EP = '%s/player/api/graphql' % _API_BASE
33 _GRAPHQL_HEADERS = {
34 'Content-Type': 'application/json;charset=UTF-8',
35 }
36 _GRAPHQL_COURSE_TMPL = '''
37query BootstrapPlayer {
38 rpc {
39 bootstrapPlayer {
40 profile {
41 firstName
42 lastName
43 email
44 username
45 userHandle
46 authed
47 isAuthed
48 plan
49 }
50 course(courseId: "%s") {
51 name
52 title
53 courseHasCaptions
54 translationLanguages {
55 code
56 name
57 }
58 supportsWideScreenVideoFormats
59 timestamp
60 modules {
61 name
62 title
63 duration
64 formattedDuration
65 author
66 authorized
67 clips {
68 authorized
69 clipId
70 duration
71 formattedDuration
72 id
73 index
74 moduleIndex
75 moduleTitle
76 name
77 title
78 watched
79 }
80 }
81 }
82 }
83 }
84}'''
85
93d0583e
S
86 def _download_course(self, course_id, url, display_id):
87 try:
88 return self._download_course_rpc(course_id, url, display_id)
89 except ExtractorError:
90 # Old API fallback
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})
95
96 def _download_course_rpc(self, course_id, url, display_id):
97 response = self._download_json(
836ef484
S
98 self._GRAPHQL_EP, display_id, data=json.dumps({
99 'query': self._GRAPHQL_COURSE_TMPL % course_id,
100 'variables': {}
101 }).encode('utf-8'), headers=self._GRAPHQL_HEADERS)
102
103 course = try_get(
104 response, lambda x: x['data']['rpc']['bootstrapPlayer']['course'],
105 dict)
93d0583e
S
106 if course:
107 return course
108
109 raise ExtractorError(
110 '%s said: %s' % (self.IE_NAME, response['error']['message']),
111 expected=True)
112
563772ed
S
113
114class PluralsightIE(PluralsightBaseIE):
483fc223 115 IE_NAME = 'pluralsight'
b0dfcab6 116 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
c3a227d1 117 _LOGIN_URL = 'https://app.pluralsight.com/id/'
563772ed 118
483fc223
S
119 _NETRC_MACHINE = 'pluralsight'
120
71bd93b8 121 _TESTS = [{
483fc223
S
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',
124 'info_dict': {
125 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
126 'ext': 'mp4',
8e5a7c5e 127 'title': 'Demo Monitoring',
483fc223
S
128 'duration': 338,
129 },
130 'skip': 'Requires pluralsight account credentials',
71bd93b8
S
131 }, {
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,
c23e2664
S
134 }, {
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,
b0dfcab6
S
138 }, {
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,
71bd93b8 141 }]
483fc223 142
836ef484
S
143 GRAPHQL_VIEWCLIP_TMPL = '''
144query viewClip {
145 viewClip(input: {
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"
154 }) {
155 urls {
156 url
157 cdn
158 rank
159 source
160 },
161 status
162 }
163}'''
164
52efa4b3 165 def _perform_login(self, username, password):
483fc223
S
166 login_page = self._download_webpage(
167 self._LOGIN_URL, None, 'Downloading login page')
168
169 login_form = self._hidden_inputs(login_page)
170
171 login_form.update({
244cd042
S
172 'Username': username,
173 'Password': password,
483fc223
S
174 })
175
176 post_url = self._search_regex(
177 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
178 'post url', default=self._LOGIN_URL, group='url')
179
180 if not post_url.startswith('http'):
181 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
182
483fc223 183 response = self._download_webpage(
e4d95865 184 post_url, None, 'Logging in',
30317f48
S
185 data=urlencode_postdata(login_form),
186 headers={'Content-Type': 'application/x-www-form-urlencoded'})
483fc223
S
187
188 error = self._search_regex(
189 r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
190 response, 'error message', default=None)
191 if error:
192 raise ExtractorError('Unable to login: %s' % error, expected=True)
193
21c1a00d
S
194 if all(not re.search(p, response) for p in (
195 r'__INITIAL_STATE__', r'["\']currentUser["\']',
196 # new layout?
197 r'>\s*Sign out\s*<')):
9dd5408c
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)
c94427dd
S
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)
208
7e508ff2
S
209 raise ExtractorError('Unable to log in')
210
36534313
S
211 def _get_subtitles(self, author, clip_idx, clip_id, lang, name, duration, video_id):
212 captions = None
213 if clip_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',
218 fatal=False)
219 if not captions:
220 captions_post = {
221 'a': author,
222 'cn': int(clip_idx),
223 'lc': lang,
224 'm': name,
225 }
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'})
8c3e35dd
S
231 if captions:
232 return {
233 lang: [{
234 'ext': 'json',
235 'data': json.dumps(captions),
236 }, {
237 'ext': 'srt',
238 'data': self._convert_subtitles(duration, captions),
239 }]
240 }
241
242 @staticmethod
243 def _convert_subtitles(duration, subs):
244 srt = ''
425f3fdf
S
245 TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
246 TEXT_KEYS = ('text', 'Text')
8c3e35dd
S
247 for num, current in enumerate(subs):
248 current = subs[num]
425f3fdf 249 start, text = (
2c8e11b4 250 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
425f3fdf 251 dict_get(current, TEXT_KEYS))
8c3e35dd
S
252 if start is None or text is None:
253 continue
254 end = duration if num == len(subs) - 1 else float_or_none(
2c8e11b4 255 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
30317f48
S
256 if end is None:
257 continue
8c3e35dd
S
258 srt += os.linesep.join(
259 (
260 '%d' % num,
261 '%s --> %s' % (
262 srt_subtitles_timecode(start),
263 srt_subtitles_timecode(end)),
264 text,
265 os.linesep,
266 ))
267 return srt
268
483fc223 269 def _real_extract(self, url):
4dfbf869 270 qs = parse_qs(url)
71bd93b8
S
271
272 author = qs.get('author', [None])[0]
273 name = qs.get('name', [None])[0]
a3f86160 274 clip_idx = qs.get('clip', [None])[0]
9df6b03c 275 course_name = qs.get('course', [None])[0]
71bd93b8 276
a3f86160 277 if any(not f for f in (author, name, clip_idx, course_name,)):
71bd93b8 278 raise ExtractorError('Invalid URL', expected=True)
483fc223 279
a3f86160 280 display_id = '%s-%s' % (name, clip_idx)
483fc223 281
93d0583e 282 course = self._download_course(course_name, url, display_id)
9df6b03c
S
283
284 collection = course['modules']
483fc223 285
d212c93d 286 clip = None
483fc223
S
287
288 for module_ in collection:
02f0da20 289 if name in (module_.get('moduleName'), module_.get('name')):
483fc223
S
290 for clip_ in module_.get('clips', []):
291 clip_index = clip_.get('clipIndex')
02f0da20
S
292 if clip_index is None:
293 clip_index = clip_.get('index')
483fc223
S
294 if clip_index is None:
295 continue
a3f86160 296 if compat_str(clip_index) == clip_idx:
483fc223
S
297 clip = clip_
298 break
299
300 if not clip:
301 raise ExtractorError('Unable to resolve clip')
302
8e5a7c5e 303 title = clip['title']
a3f86160 304 clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
8c3e35dd 305
483fc223
S
306 QUALITIES = {
307 'low': {'width': 640, 'height': 480},
308 'medium': {'width': 848, 'height': 640},
309 'high': {'width': 1024, 'height': 768},
756926ff 310 'high-widescreen': {'width': 1280, 'height': 720},
483fc223
S
311 }
312
756926ff
S
313 QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
314 quality_key = qualities(QUALITIES_PREFERENCE)
315
4c57b485
S
316 AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
317
483fc223 318 ALLOWED_QUALITIES = (
756926ff
S
319 AllowedQuality('webm', ['high', ]),
320 AllowedQuality('mp4', ['low', 'medium', 'high', ]),
483fc223
S
321 )
322
756926ff 323 # Some courses also offer widescreen resolution for high quality (see
067aa17e 324 # https://github.com/ytdl-org/youtube-dl/issues/7766)
9df6b03c 325 widescreen = course.get('supportsWideScreenVideoFormats') is True
756926ff
S
326 best_quality = 'high-widescreen' if widescreen else 'high'
327 if widescreen:
328 for allowed_quality in ALLOWED_QUALITIES:
329 allowed_quality.qualities.append(best_quality)
330
cf186b77
S
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
0eebf34d 333 # only single format until formats listing was explicitly requested.
a06916d9 334 if self.get_param('listformats', False):
4c57b485
S
335 allowed_qualities = ALLOWED_QUALITIES
336 else:
337 def guess_allowed_qualities():
a06916d9 338 req_format = self.get_param('format') or 'best'
edc70f4a 339 req_format_split = req_format.split('-', 1)
4c57b485
S
340 if len(req_format_split) > 1:
341 req_ext, req_quality = req_format_split
fac188c6 342 req_quality = '-'.join(req_quality.split('-')[:2])
4c57b485
S
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, )), )
a06916d9 346 req_ext = 'webm' if self.get_param('prefer_free_formats') else 'mp4'
756926ff 347 return (AllowedQuality(req_ext, (best_quality, )), )
4c57b485
S
348 allowed_qualities = guess_allowed_qualities()
349
483fc223 350 formats = []
756926ff
S
351 for ext, qualities_ in allowed_qualities:
352 for quality in qualities_:
483fc223
S
353 f = QUALITIES[quality].copy()
354 clip_post = {
9df6b03c 355 'author': author,
836ef484 356 'includeCaptions': 'false',
a3f86160 357 'clipIndex': int(clip_idx),
9df6b03c
S
358 'courseName': course_name,
359 'locale': 'en',
360 'moduleName': name,
361 'mediaType': ext,
362 'quality': '%dx%d' % (f['width'], f['height']),
483fc223 363 }
483fc223 364 format_id = '%s-%s' % (ext, quality)
836ef484
S
365
366 try:
367 viewclip = self._download_json(
368 self._GRAPHQL_EP, display_id,
369 'Downloading %s viewclip graphql' % format_id,
370 data=json.dumps({
371 'query': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
372 'variables': {}
373 }).encode('utf-8'),
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'})
38eb2968
S
382
383 # Pluralsight tracks multiple sequential calls to ViewClip API and start
384 # to return 429 HTTP errors after some time (see
067aa17e
S
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).
38eb2968
S
387 # To somewhat reduce the probability of these consequences
388 # we will sleep random amount of time before each call to ViewClip.
389 self._sleep(
201c1459 390 random.randint(5, 10), display_id,
38eb2968
S
391 '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
392
f8ae2c7f 393 if not viewclip:
483fc223 394 continue
f8ae2c7f
S
395
396 clip_urls = viewclip.get('urls')
397 if not isinstance(clip_urls, list):
398 continue
399
400 for clip_url_data in clip_urls:
401 clip_url = clip_url_data.get('url')
402 if not clip_url:
403 continue
404 cdn = clip_url_data.get('cdn')
405 clip_f = f.copy()
406 clip_f.update({
407 'url': clip_url,
408 'ext': ext,
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')),
412 })
413 formats.append(clip_f)
414
483fc223
S
415 self._sort_formats(formats)
416
8c3e35dd
S
417 duration = int_or_none(
418 clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
419
420 # TODO: other languages?
421 subtitles = self.extract_subtitles(
36534313 422 author, clip_idx, clip.get('clipId'), 'en', name, duration, display_id)
483fc223
S
423
424 return {
a3f86160 425 'id': clip_id,
8c3e35dd
S
426 'title': title,
427 'duration': duration,
483fc223 428 'creator': author,
8c3e35dd
S
429 'formats': formats,
430 'subtitles': subtitles,
483fc223
S
431 }
432
433
563772ed 434class PluralsightCourseIE(PluralsightBaseIE):
483fc223 435 IE_NAME = 'pluralsight:course'
a5cd0eb8 436 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
c23e2664 437 _TESTS = [{
483fc223
S
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',
441 'info_dict': {
442 'id': 'hosting-sql-server-windows-azure-iaas',
443 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
444 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
445 },
446 'playlist_count': 31,
c23e2664
S
447 }, {
448 # available without pluralsight account
449 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
450 'only_matching': True,
a5cd0eb8
S
451 }, {
452 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
453 'only_matching': True,
c23e2664 454 }]
483fc223
S
455
456 def _real_extract(self, url):
457 course_id = self._match_id(url)
458
2b6bda1e
S
459 # TODO: PSM cookie
460
93d0583e 461 course = self._download_course(course_id, url, course_id)
483fc223
S
462
463 title = course['title']
3d7e3aaa
S
464 course_name = course['name']
465 course_data = course['modules']
483fc223
S
466 description = course.get('description') or course.get('shortDescription')
467
483fc223 468 entries = []
8018028d 469 for num, module in enumerate(course_data, 1):
3d7e3aaa
S
470 author = module.get('author')
471 module_name = module.get('name')
472 if not author or not module_name:
473 continue
483fc223 474 for clip in module.get('clips', []):
3d7e3aaa
S
475 clip_index = int_or_none(clip.get('index'))
476 if clip_index is None:
483fc223 477 continue
3d7e3aaa
S
478 clip_url = update_url_query(
479 '%s/player' % self._API_BASE, query={
480 'mode': 'live',
481 'course': course_name,
482 'author': author,
483 'name': module_name,
484 'clip': clip_index,
485 })
8018028d
S
486 entries.append({
487 '_type': 'url_transparent',
3d7e3aaa 488 'url': clip_url,
8018028d
S
489 'ie_key': PluralsightIE.ie_key(),
490 'chapter': module.get('title'),
491 'chapter_number': num,
492 'chapter_id': module.get('moduleRef'),
493 })
483fc223 494
483fc223 495 return self.playlist_result(entries, course_id, title, description)