]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/pluralsight.py
[utils] Add `parse_qs`
[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 _real_initialize(self):
166 self._login()
167
168 def _login(self):
169 username, password = self._get_login_info()
170 if username is None:
171 return
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({
179 'Username': username,
180 'Password': password,
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
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'})
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
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*<')):
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)
215
216 raise ExtractorError('Unable to log in')
217
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'})
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 = ''
252 TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
253 TEXT_KEYS = ('text', 'Text')
254 for num, current in enumerate(subs):
255 current = subs[num]
256 start, text = (
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:
260 continue
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))
263 if end is None:
264 continue
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
276 def _real_extract(self, url):
277 qs = parse_qs(url)
278
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]
283
284 if any(not f for f in (author, name, clip_idx, course_name,)):
285 raise ExtractorError('Invalid URL', expected=True)
286
287 display_id = '%s-%s' % (name, clip_idx)
288
289 course = self._download_course(course_name, url, display_id)
290
291 collection = course['modules']
292
293 clip = None
294
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:
302 continue
303 if compat_str(clip_index) == clip_idx:
304 clip = clip_
305 break
306
307 if not clip:
308 raise ExtractorError('Unable to resolve clip')
309
310 title = clip['title']
311 clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
312
313 QUALITIES = {
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},
318 }
319
320 QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
321 quality_key = qualities(QUALITIES_PREFERENCE)
322
323 AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
324
325 ALLOWED_QUALITIES = (
326 AllowedQuality('webm', ['high', ]),
327 AllowedQuality('mp4', ['low', 'medium', 'high', ]),
328 )
329
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'
334 if widescreen:
335 for allowed_quality in ALLOWED_QUALITIES:
336 allowed_quality.qualities.append(best_quality)
337
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
343 else:
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()
356
357 formats = []
358 for ext, qualities_ in allowed_qualities:
359 for quality in qualities_:
360 f = QUALITIES[quality].copy()
361 clip_post = {
362 'author': author,
363 'includeCaptions': 'false',
364 'clipIndex': int(clip_idx),
365 'courseName': course_name,
366 'locale': 'en',
367 'moduleName': name,
368 'mediaType': ext,
369 'quality': '%dx%d' % (f['width'], f['height']),
370 }
371 format_id = '%s-%s' % (ext, quality)
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'})
389
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.
396 self._sleep(
397 random.randint(5, 10), display_id,
398 '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
399
400 if not viewclip:
401 continue
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
422 self._sort_formats(formats)
423
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(
429 author, clip_idx, clip.get('clipId'), 'en', name, duration, display_id)
430
431 return {
432 'id': clip_id,
433 'title': title,
434 'duration': duration,
435 'creator': author,
436 'formats': formats,
437 'subtitles': subtitles,
438 }
439
440
441 class PluralsightCourseIE(PluralsightBaseIE):
442 IE_NAME = 'pluralsight:course'
443 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
444 _TESTS = [{
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,
454 }, {
455 # available without pluralsight account
456 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
457 'only_matching': True,
458 }, {
459 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
460 'only_matching': True,
461 }]
462
463 def _real_extract(self, url):
464 course_id = self._match_id(url)
465
466 # TODO: PSM cookie
467
468 course = self._download_course(course_id, url, course_id)
469
470 title = course['title']
471 course_name = course['name']
472 course_data = course['modules']
473 description = course.get('description') or course.get('shortDescription')
474
475 entries = []
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:
480 continue
481 for clip in module.get('clips', []):
482 clip_index = int_or_none(clip.get('index'))
483 if clip_index is None:
484 continue
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 })
493 entries.append({
494 '_type': 'url_transparent',
495 'url': clip_url,
496 'ie_key': PluralsightIE.ie_key(),
497 'chapter': module.get('title'),
498 'chapter_number': num,
499 'chapter_id': module.get('moduleRef'),
500 })
501
502 return self.playlist_result(entries, course_id, title, description)