]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/pluralsight.py
[utils] Add `parse_qs`
[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
483fc223
S
165 def _real_initialize(self):
166 self._login()
167
168 def _login(self):
68217024 169 username, password = self._get_login_info()
483fc223 170 if username is None:
c23e2664 171 return
483fc223
S
172
173 login_page = self._download_webpage(
174 self._LOGIN_URL, None, 'Downloading login page')
175
176 login_form = self._hidden_inputs(login_page)
177
178 login_form.update({
244cd042
S
179 'Username': username,
180 'Password': password,
483fc223
S
181 })
182
183 post_url = self._search_regex(
184 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
185 'post url', default=self._LOGIN_URL, group='url')
186
187 if not post_url.startswith('http'):
188 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
189
483fc223 190 response = self._download_webpage(
e4d95865 191 post_url, None, 'Logging in',
30317f48
S
192 data=urlencode_postdata(login_form),
193 headers={'Content-Type': 'application/x-www-form-urlencoded'})
483fc223
S
194
195 error = self._search_regex(
196 r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
197 response, 'error message', default=None)
198 if error:
199 raise ExtractorError('Unable to login: %s' % error, expected=True)
200
21c1a00d
S
201 if all(not re.search(p, response) for p in (
202 r'__INITIAL_STATE__', r'["\']currentUser["\']',
203 # new layout?
204 r'>\s*Sign out\s*<')):
9dd5408c
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)
c94427dd
S
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)
215
7e508ff2
S
216 raise ExtractorError('Unable to log in')
217
36534313
S
218 def _get_subtitles(self, author, clip_idx, clip_id, lang, name, duration, video_id):
219 captions = None
220 if clip_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',
225 fatal=False)
226 if not captions:
227 captions_post = {
228 'a': author,
229 'cn': int(clip_idx),
230 'lc': lang,
231 'm': name,
232 }
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'})
8c3e35dd
S
238 if captions:
239 return {
240 lang: [{
241 'ext': 'json',
242 'data': json.dumps(captions),
243 }, {
244 'ext': 'srt',
245 'data': self._convert_subtitles(duration, captions),
246 }]
247 }
248
249 @staticmethod
250 def _convert_subtitles(duration, subs):
251 srt = ''
425f3fdf
S
252 TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
253 TEXT_KEYS = ('text', 'Text')
8c3e35dd
S
254 for num, current in enumerate(subs):
255 current = subs[num]
425f3fdf 256 start, text = (
2c8e11b4 257 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
425f3fdf 258 dict_get(current, TEXT_KEYS))
8c3e35dd
S
259 if start is None or text is None:
260 continue
261 end = duration if num == len(subs) - 1 else float_or_none(
2c8e11b4 262 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
30317f48
S
263 if end is None:
264 continue
8c3e35dd
S
265 srt += os.linesep.join(
266 (
267 '%d' % num,
268 '%s --> %s' % (
269 srt_subtitles_timecode(start),
270 srt_subtitles_timecode(end)),
271 text,
272 os.linesep,
273 ))
274 return srt
275
483fc223 276 def _real_extract(self, url):
4dfbf869 277 qs = parse_qs(url)
71bd93b8
S
278
279 author = qs.get('author', [None])[0]
280 name = qs.get('name', [None])[0]
a3f86160 281 clip_idx = qs.get('clip', [None])[0]
9df6b03c 282 course_name = qs.get('course', [None])[0]
71bd93b8 283
a3f86160 284 if any(not f for f in (author, name, clip_idx, course_name,)):
71bd93b8 285 raise ExtractorError('Invalid URL', expected=True)
483fc223 286
a3f86160 287 display_id = '%s-%s' % (name, clip_idx)
483fc223 288
93d0583e 289 course = self._download_course(course_name, url, display_id)
9df6b03c
S
290
291 collection = course['modules']
483fc223 292
d212c93d 293 clip = None
483fc223
S
294
295 for module_ in collection:
02f0da20 296 if name in (module_.get('moduleName'), module_.get('name')):
483fc223
S
297 for clip_ in module_.get('clips', []):
298 clip_index = clip_.get('clipIndex')
02f0da20
S
299 if clip_index is None:
300 clip_index = clip_.get('index')
483fc223
S
301 if clip_index is None:
302 continue
a3f86160 303 if compat_str(clip_index) == clip_idx:
483fc223
S
304 clip = clip_
305 break
306
307 if not clip:
308 raise ExtractorError('Unable to resolve clip')
309
8e5a7c5e 310 title = clip['title']
a3f86160 311 clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
8c3e35dd 312
483fc223
S
313 QUALITIES = {
314 'low': {'width': 640, 'height': 480},
315 'medium': {'width': 848, 'height': 640},
316 'high': {'width': 1024, 'height': 768},
756926ff 317 'high-widescreen': {'width': 1280, 'height': 720},
483fc223
S
318 }
319
756926ff
S
320 QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
321 quality_key = qualities(QUALITIES_PREFERENCE)
322
4c57b485
S
323 AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
324
483fc223 325 ALLOWED_QUALITIES = (
756926ff
S
326 AllowedQuality('webm', ['high', ]),
327 AllowedQuality('mp4', ['low', 'medium', 'high', ]),
483fc223
S
328 )
329
756926ff 330 # Some courses also offer widescreen resolution for high quality (see
067aa17e 331 # https://github.com/ytdl-org/youtube-dl/issues/7766)
9df6b03c 332 widescreen = course.get('supportsWideScreenVideoFormats') is True
756926ff
S
333 best_quality = 'high-widescreen' if widescreen else 'high'
334 if widescreen:
335 for allowed_quality in ALLOWED_QUALITIES:
336 allowed_quality.qualities.append(best_quality)
337
cf186b77
S
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
0eebf34d 340 # only single format until formats listing was explicitly requested.
a06916d9 341 if self.get_param('listformats', False):
4c57b485
S
342 allowed_qualities = ALLOWED_QUALITIES
343 else:
344 def guess_allowed_qualities():
a06916d9 345 req_format = self.get_param('format') or 'best'
edc70f4a 346 req_format_split = req_format.split('-', 1)
4c57b485
S
347 if len(req_format_split) > 1:
348 req_ext, req_quality = req_format_split
fac188c6 349 req_quality = '-'.join(req_quality.split('-')[:2])
4c57b485
S
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, )), )
a06916d9 353 req_ext = 'webm' if self.get_param('prefer_free_formats') else 'mp4'
756926ff 354 return (AllowedQuality(req_ext, (best_quality, )), )
4c57b485
S
355 allowed_qualities = guess_allowed_qualities()
356
483fc223 357 formats = []
756926ff
S
358 for ext, qualities_ in allowed_qualities:
359 for quality in qualities_:
483fc223
S
360 f = QUALITIES[quality].copy()
361 clip_post = {
9df6b03c 362 'author': author,
836ef484 363 'includeCaptions': 'false',
a3f86160 364 'clipIndex': int(clip_idx),
9df6b03c
S
365 'courseName': course_name,
366 'locale': 'en',
367 'moduleName': name,
368 'mediaType': ext,
369 'quality': '%dx%d' % (f['width'], f['height']),
483fc223 370 }
483fc223 371 format_id = '%s-%s' % (ext, quality)
836ef484
S
372
373 try:
374 viewclip = self._download_json(
375 self._GRAPHQL_EP, display_id,
376 'Downloading %s viewclip graphql' % format_id,
377 data=json.dumps({
378 'query': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
379 'variables': {}
380 }).encode('utf-8'),
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'})
38eb2968
S
389
390 # Pluralsight tracks multiple sequential calls to ViewClip API and start
391 # to return 429 HTTP errors after some time (see
067aa17e
S
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).
38eb2968
S
394 # To somewhat reduce the probability of these consequences
395 # we will sleep random amount of time before each call to ViewClip.
396 self._sleep(
201c1459 397 random.randint(5, 10), display_id,
38eb2968
S
398 '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
399
f8ae2c7f 400 if not viewclip:
483fc223 401 continue
f8ae2c7f
S
402
403 clip_urls = viewclip.get('urls')
404 if not isinstance(clip_urls, list):
405 continue
406
407 for clip_url_data in clip_urls:
408 clip_url = clip_url_data.get('url')
409 if not clip_url:
410 continue
411 cdn = clip_url_data.get('cdn')
412 clip_f = f.copy()
413 clip_f.update({
414 'url': clip_url,
415 'ext': ext,
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')),
419 })
420 formats.append(clip_f)
421
483fc223
S
422 self._sort_formats(formats)
423
8c3e35dd
S
424 duration = int_or_none(
425 clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
426
427 # TODO: other languages?
428 subtitles = self.extract_subtitles(
36534313 429 author, clip_idx, clip.get('clipId'), 'en', name, duration, display_id)
483fc223
S
430
431 return {
a3f86160 432 'id': clip_id,
8c3e35dd
S
433 'title': title,
434 'duration': duration,
483fc223 435 'creator': author,
8c3e35dd
S
436 'formats': formats,
437 'subtitles': subtitles,
483fc223
S
438 }
439
440
563772ed 441class PluralsightCourseIE(PluralsightBaseIE):
483fc223 442 IE_NAME = 'pluralsight:course'
a5cd0eb8 443 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
c23e2664 444 _TESTS = [{
483fc223
S
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',
448 'info_dict': {
449 'id': 'hosting-sql-server-windows-azure-iaas',
450 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
451 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
452 },
453 'playlist_count': 31,
c23e2664
S
454 }, {
455 # available without pluralsight account
456 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
457 'only_matching': True,
a5cd0eb8
S
458 }, {
459 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
460 'only_matching': True,
c23e2664 461 }]
483fc223
S
462
463 def _real_extract(self, url):
464 course_id = self._match_id(url)
465
2b6bda1e
S
466 # TODO: PSM cookie
467
93d0583e 468 course = self._download_course(course_id, url, course_id)
483fc223
S
469
470 title = course['title']
3d7e3aaa
S
471 course_name = course['name']
472 course_data = course['modules']
483fc223
S
473 description = course.get('description') or course.get('shortDescription')
474
483fc223 475 entries = []
8018028d 476 for num, module in enumerate(course_data, 1):
3d7e3aaa
S
477 author = module.get('author')
478 module_name = module.get('name')
479 if not author or not module_name:
480 continue
483fc223 481 for clip in module.get('clips', []):
3d7e3aaa
S
482 clip_index = int_or_none(clip.get('index'))
483 if clip_index is None:
483fc223 484 continue
3d7e3aaa
S
485 clip_url = update_url_query(
486 '%s/player' % self._API_BASE, query={
487 'mode': 'live',
488 'course': course_name,
489 'author': author,
490 'name': module_name,
491 'clip': clip_index,
492 })
8018028d
S
493 entries.append({
494 '_type': 'url_transparent',
3d7e3aaa 495 'url': clip_url,
8018028d
S
496 'ie_key': PluralsightIE.ie_key(),
497 'chapter': module.get('title'),
498 'chapter_number': num,
499 'chapter_id': module.get('moduleRef'),
500 })
483fc223 501
483fc223 502 return self.playlist_result(entries, course_id, title, description)