]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/pluralsight.py
[extractor] Add `_perform_login` function (#2943)
[yt-dlp.git] / yt_dlp / extractor / pluralsight.py
1 from __future__ import unicode_literals
2
3 import collections
4 import json
5 import os
6 import random
7 import re
8
9 from .common import InfoExtractor
10 from ..compat import (
11 compat_str,
12 compat_urlparse,
13 )
14 from ..utils import (
15 dict_get,
16 ExtractorError,
17 float_or_none,
18 int_or_none,
19 parse_duration,
20 parse_qs,
21 qualities,
22 srt_subtitles_timecode,
23 try_get,
24 update_url_query,
25 urlencode_postdata,
26 )
27
28
29 class PluralsightBaseIE(InfoExtractor):
30 _API_BASE = 'https://app.pluralsight.com'
31
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 = '''
37 query 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
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(
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)
106 if course:
107 return course
108
109 raise ExtractorError(
110 '%s said: %s' % (self.IE_NAME, response['error']['message']),
111 expected=True)
112
113
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/'
118
119 _NETRC_MACHINE = 'pluralsight'
120
121 _TESTS = [{
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',
127 'title': 'Demo Monitoring',
128 'duration': 338,
129 },
130 'skip': 'Requires pluralsight account credentials',
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,
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,
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,
141 }]
142
143 GRAPHQL_VIEWCLIP_TMPL = '''
144 query 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
165 def _perform_login(self, username, password):
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({
172 'Username': username,
173 'Password': password,
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
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'})
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
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*<')):
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)
208
209 raise ExtractorError('Unable to log in')
210
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'})
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 = ''
245 TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
246 TEXT_KEYS = ('text', 'Text')
247 for num, current in enumerate(subs):
248 current = subs[num]
249 start, text = (
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:
253 continue
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))
256 if end is None:
257 continue
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
269 def _real_extract(self, url):
270 qs = parse_qs(url)
271
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]
276
277 if any(not f for f in (author, name, clip_idx, course_name,)):
278 raise ExtractorError('Invalid URL', expected=True)
279
280 display_id = '%s-%s' % (name, clip_idx)
281
282 course = self._download_course(course_name, url, display_id)
283
284 collection = course['modules']
285
286 clip = None
287
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:
295 continue
296 if compat_str(clip_index) == clip_idx:
297 clip = clip_
298 break
299
300 if not clip:
301 raise ExtractorError('Unable to resolve clip')
302
303 title = clip['title']
304 clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
305
306 QUALITIES = {
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},
311 }
312
313 QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
314 quality_key = qualities(QUALITIES_PREFERENCE)
315
316 AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
317
318 ALLOWED_QUALITIES = (
319 AllowedQuality('webm', ['high', ]),
320 AllowedQuality('mp4', ['low', 'medium', 'high', ]),
321 )
322
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'
327 if widescreen:
328 for allowed_quality in ALLOWED_QUALITIES:
329 allowed_quality.qualities.append(best_quality)
330
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
336 else:
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()
349
350 formats = []
351 for ext, qualities_ in allowed_qualities:
352 for quality in qualities_:
353 f = QUALITIES[quality].copy()
354 clip_post = {
355 'author': author,
356 'includeCaptions': 'false',
357 'clipIndex': int(clip_idx),
358 'courseName': course_name,
359 'locale': 'en',
360 'moduleName': name,
361 'mediaType': ext,
362 'quality': '%dx%d' % (f['width'], f['height']),
363 }
364 format_id = '%s-%s' % (ext, quality)
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'})
382
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.
389 self._sleep(
390 random.randint(5, 10), display_id,
391 '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
392
393 if not viewclip:
394 continue
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
415 self._sort_formats(formats)
416
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(
422 author, clip_idx, clip.get('clipId'), 'en', name, duration, display_id)
423
424 return {
425 'id': clip_id,
426 'title': title,
427 'duration': duration,
428 'creator': author,
429 'formats': formats,
430 'subtitles': subtitles,
431 }
432
433
434 class PluralsightCourseIE(PluralsightBaseIE):
435 IE_NAME = 'pluralsight:course'
436 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
437 _TESTS = [{
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,
447 }, {
448 # available without pluralsight account
449 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
450 'only_matching': True,
451 }, {
452 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
453 'only_matching': True,
454 }]
455
456 def _real_extract(self, url):
457 course_id = self._match_id(url)
458
459 # TODO: PSM cookie
460
461 course = self._download_course(course_id, url, course_id)
462
463 title = course['title']
464 course_name = course['name']
465 course_data = course['modules']
466 description = course.get('description') or course.get('shortDescription')
467
468 entries = []
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:
473 continue
474 for clip in module.get('clips', []):
475 clip_index = int_or_none(clip.get('index'))
476 if clip_index is None:
477 continue
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 })
486 entries.append({
487 '_type': 'url_transparent',
488 'url': clip_url,
489 'ie_key': PluralsightIE.ie_key(),
490 'chapter': module.get('title'),
491 'chapter_number': num,
492 'chapter_id': module.get('moduleRef'),
493 })
494
495 return self.playlist_result(entries, course_id, title, description)