]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/pluralsight.py
Update changelog.
[youtubedl] / youtube_dl / extractor / pluralsight.py
1 from __future__ import unicode_literals
2
3 import collections
4 import json
5 import os
6 import random
7
8 from .common import InfoExtractor
9 from ..compat import (
10 compat_str,
11 compat_urlparse,
12 )
13 from ..utils import (
14 dict_get,
15 ExtractorError,
16 float_or_none,
17 int_or_none,
18 parse_duration,
19 qualities,
20 srt_subtitles_timecode,
21 try_get,
22 update_url_query,
23 urlencode_postdata,
24 )
25
26
27 class PluralsightBaseIE(InfoExtractor):
28 _API_BASE = 'https://app.pluralsight.com'
29
30 _GRAPHQL_EP = '%s/player/api/graphql' % _API_BASE
31 _GRAPHQL_HEADERS = {
32 'Content-Type': 'application/json;charset=UTF-8',
33 }
34 _GRAPHQL_COURSE_TMPL = '''
35 query BootstrapPlayer {
36 rpc {
37 bootstrapPlayer {
38 profile {
39 firstName
40 lastName
41 email
42 username
43 userHandle
44 authed
45 isAuthed
46 plan
47 }
48 course(courseId: "%s") {
49 name
50 title
51 courseHasCaptions
52 translationLanguages {
53 code
54 name
55 }
56 supportsWideScreenVideoFormats
57 timestamp
58 modules {
59 name
60 title
61 duration
62 formattedDuration
63 author
64 authorized
65 clips {
66 authorized
67 clipId
68 duration
69 formattedDuration
70 id
71 index
72 moduleIndex
73 moduleTitle
74 name
75 title
76 watched
77 }
78 }
79 }
80 }
81 }
82 }'''
83
84 def _download_course(self, course_id, url, display_id):
85 try:
86 return self._download_course_rpc(course_id, url, display_id)
87 except ExtractorError:
88 # Old API fallback
89 return self._download_json(
90 'https://app.pluralsight.com/player/user/api/v1/player/payload',
91 display_id, data=urlencode_postdata({'courseId': course_id}),
92 headers={'Referer': url})
93
94 def _download_course_rpc(self, course_id, url, display_id):
95 response = self._download_json(
96 self._GRAPHQL_EP, display_id, data=json.dumps({
97 'query': self._GRAPHQL_COURSE_TMPL % course_id,
98 'variables': {}
99 }).encode('utf-8'), headers=self._GRAPHQL_HEADERS)
100
101 course = try_get(
102 response, lambda x: x['data']['rpc']['bootstrapPlayer']['course'],
103 dict)
104 if course:
105 return course
106
107 raise ExtractorError(
108 '%s said: %s' % (self.IE_NAME, response['error']['message']),
109 expected=True)
110
111
112 class PluralsightIE(PluralsightBaseIE):
113 IE_NAME = 'pluralsight'
114 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
115 _LOGIN_URL = 'https://app.pluralsight.com/id/'
116
117 _NETRC_MACHINE = 'pluralsight'
118
119 _TESTS = [{
120 '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',
121 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
122 'info_dict': {
123 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
124 'ext': 'mp4',
125 'title': 'Demo Monitoring',
126 'duration': 338,
127 },
128 'skip': 'Requires pluralsight account credentials',
129 }, {
130 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
131 'only_matching': True,
132 }, {
133 # available without pluralsight account
134 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
135 'only_matching': True,
136 }, {
137 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
138 'only_matching': True,
139 }]
140
141 GRAPHQL_VIEWCLIP_TMPL = '''
142 query viewClip {
143 viewClip(input: {
144 author: "%(author)s",
145 clipIndex: %(clipIndex)d,
146 courseName: "%(courseName)s",
147 includeCaptions: %(includeCaptions)s,
148 locale: "%(locale)s",
149 mediaType: "%(mediaType)s",
150 moduleName: "%(moduleName)s",
151 quality: "%(quality)s"
152 }) {
153 urls {
154 url
155 cdn
156 rank
157 source
158 },
159 status
160 }
161 }'''
162
163 def _real_initialize(self):
164 self._login()
165
166 def _login(self):
167 username, password = self._get_login_info()
168 if username is None:
169 return
170
171 login_page = self._download_webpage(
172 self._LOGIN_URL, None, 'Downloading login page')
173
174 login_form = self._hidden_inputs(login_page)
175
176 login_form.update({
177 'Username': username,
178 'Password': password,
179 })
180
181 post_url = self._search_regex(
182 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
183 'post url', default=self._LOGIN_URL, group='url')
184
185 if not post_url.startswith('http'):
186 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
187
188 response = self._download_webpage(
189 post_url, None, 'Logging in',
190 data=urlencode_postdata(login_form),
191 headers={'Content-Type': 'application/x-www-form-urlencoded'})
192
193 error = self._search_regex(
194 r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
195 response, 'error message', default=None)
196 if error:
197 raise ExtractorError('Unable to login: %s' % error, expected=True)
198
199 if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
200 BLOCKED = 'Your account has been blocked due to suspicious activity'
201 if BLOCKED in response:
202 raise ExtractorError(
203 'Unable to login: %s' % BLOCKED, expected=True)
204 MUST_AGREE = 'To continue using Pluralsight, you must agree to'
205 if any(p in response for p in (MUST_AGREE, '>Disagree<', '>Agree<')):
206 raise ExtractorError(
207 'Unable to login: %s some documents. Go to pluralsight.com, '
208 'log in and agree with what Pluralsight requires.'
209 % MUST_AGREE, expected=True)
210
211 raise ExtractorError('Unable to log in')
212
213 def _get_subtitles(self, author, clip_idx, lang, name, duration, video_id):
214 captions_post = {
215 'a': author,
216 'cn': clip_idx,
217 'lc': lang,
218 'm': name,
219 }
220 captions = self._download_json(
221 '%s/player/retrieve-captions' % self._API_BASE, video_id,
222 'Downloading captions JSON', 'Unable to download captions JSON',
223 fatal=False, data=json.dumps(captions_post).encode('utf-8'),
224 headers={'Content-Type': 'application/json;charset=utf-8'})
225 if captions:
226 return {
227 lang: [{
228 'ext': 'json',
229 'data': json.dumps(captions),
230 }, {
231 'ext': 'srt',
232 'data': self._convert_subtitles(duration, captions),
233 }]
234 }
235
236 @staticmethod
237 def _convert_subtitles(duration, subs):
238 srt = ''
239 TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
240 TEXT_KEYS = ('text', 'Text')
241 for num, current in enumerate(subs):
242 current = subs[num]
243 start, text = (
244 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
245 dict_get(current, TEXT_KEYS))
246 if start is None or text is None:
247 continue
248 end = duration if num == len(subs) - 1 else float_or_none(
249 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
250 if end is None:
251 continue
252 srt += os.linesep.join(
253 (
254 '%d' % num,
255 '%s --> %s' % (
256 srt_subtitles_timecode(start),
257 srt_subtitles_timecode(end)),
258 text,
259 os.linesep,
260 ))
261 return srt
262
263 def _real_extract(self, url):
264 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
265
266 author = qs.get('author', [None])[0]
267 name = qs.get('name', [None])[0]
268 clip_idx = qs.get('clip', [None])[0]
269 course_name = qs.get('course', [None])[0]
270
271 if any(not f for f in (author, name, clip_idx, course_name,)):
272 raise ExtractorError('Invalid URL', expected=True)
273
274 display_id = '%s-%s' % (name, clip_idx)
275
276 course = self._download_course(course_name, url, display_id)
277
278 collection = course['modules']
279
280 clip = None
281
282 for module_ in collection:
283 if name in (module_.get('moduleName'), module_.get('name')):
284 for clip_ in module_.get('clips', []):
285 clip_index = clip_.get('clipIndex')
286 if clip_index is None:
287 clip_index = clip_.get('index')
288 if clip_index is None:
289 continue
290 if compat_str(clip_index) == clip_idx:
291 clip = clip_
292 break
293
294 if not clip:
295 raise ExtractorError('Unable to resolve clip')
296
297 title = clip['title']
298 clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
299
300 QUALITIES = {
301 'low': {'width': 640, 'height': 480},
302 'medium': {'width': 848, 'height': 640},
303 'high': {'width': 1024, 'height': 768},
304 'high-widescreen': {'width': 1280, 'height': 720},
305 }
306
307 QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
308 quality_key = qualities(QUALITIES_PREFERENCE)
309
310 AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
311
312 ALLOWED_QUALITIES = (
313 AllowedQuality('webm', ['high', ]),
314 AllowedQuality('mp4', ['low', 'medium', 'high', ]),
315 )
316
317 # Some courses also offer widescreen resolution for high quality (see
318 # https://github.com/rg3/youtube-dl/issues/7766)
319 widescreen = course.get('supportsWideScreenVideoFormats') is True
320 best_quality = 'high-widescreen' if widescreen else 'high'
321 if widescreen:
322 for allowed_quality in ALLOWED_QUALITIES:
323 allowed_quality.qualities.append(best_quality)
324
325 # In order to minimize the number of calls to ViewClip API and reduce
326 # the probability of being throttled or banned by Pluralsight we will request
327 # only single format until formats listing was explicitly requested.
328 if self._downloader.params.get('listformats', False):
329 allowed_qualities = ALLOWED_QUALITIES
330 else:
331 def guess_allowed_qualities():
332 req_format = self._downloader.params.get('format') or 'best'
333 req_format_split = req_format.split('-', 1)
334 if len(req_format_split) > 1:
335 req_ext, req_quality = req_format_split
336 req_quality = '-'.join(req_quality.split('-')[:2])
337 for allowed_quality in ALLOWED_QUALITIES:
338 if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
339 return (AllowedQuality(req_ext, (req_quality, )), )
340 req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
341 return (AllowedQuality(req_ext, (best_quality, )), )
342 allowed_qualities = guess_allowed_qualities()
343
344 formats = []
345 for ext, qualities_ in allowed_qualities:
346 for quality in qualities_:
347 f = QUALITIES[quality].copy()
348 clip_post = {
349 'author': author,
350 'includeCaptions': 'false',
351 'clipIndex': int(clip_idx),
352 'courseName': course_name,
353 'locale': 'en',
354 'moduleName': name,
355 'mediaType': ext,
356 'quality': '%dx%d' % (f['width'], f['height']),
357 }
358 format_id = '%s-%s' % (ext, quality)
359
360 try:
361 viewclip = self._download_json(
362 self._GRAPHQL_EP, display_id,
363 'Downloading %s viewclip graphql' % format_id,
364 data=json.dumps({
365 'query': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
366 'variables': {}
367 }).encode('utf-8'),
368 headers=self._GRAPHQL_HEADERS)['data']['viewClip']
369 except ExtractorError:
370 # Still works but most likely will go soon
371 viewclip = self._download_json(
372 '%s/video/clips/viewclip' % self._API_BASE, display_id,
373 'Downloading %s viewclip JSON' % format_id, fatal=False,
374 data=json.dumps(clip_post).encode('utf-8'),
375 headers={'Content-Type': 'application/json;charset=utf-8'})
376
377 # Pluralsight tracks multiple sequential calls to ViewClip API and start
378 # to return 429 HTTP errors after some time (see
379 # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
380 # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
381 # To somewhat reduce the probability of these consequences
382 # we will sleep random amount of time before each call to ViewClip.
383 self._sleep(
384 random.randint(2, 5), display_id,
385 '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
386
387 if not viewclip:
388 continue
389
390 clip_urls = viewclip.get('urls')
391 if not isinstance(clip_urls, list):
392 continue
393
394 for clip_url_data in clip_urls:
395 clip_url = clip_url_data.get('url')
396 if not clip_url:
397 continue
398 cdn = clip_url_data.get('cdn')
399 clip_f = f.copy()
400 clip_f.update({
401 'url': clip_url,
402 'ext': ext,
403 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
404 'quality': quality_key(quality),
405 'source_preference': int_or_none(clip_url_data.get('rank')),
406 })
407 formats.append(clip_f)
408
409 self._sort_formats(formats)
410
411 duration = int_or_none(
412 clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
413
414 # TODO: other languages?
415 subtitles = self.extract_subtitles(
416 author, clip_idx, 'en', name, duration, display_id)
417
418 return {
419 'id': clip_id,
420 'title': title,
421 'duration': duration,
422 'creator': author,
423 'formats': formats,
424 'subtitles': subtitles,
425 }
426
427
428 class PluralsightCourseIE(PluralsightBaseIE):
429 IE_NAME = 'pluralsight:course'
430 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
431 _TESTS = [{
432 # Free course from Pluralsight Starter Subscription for Microsoft TechNet
433 # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
434 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
435 'info_dict': {
436 'id': 'hosting-sql-server-windows-azure-iaas',
437 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
438 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
439 },
440 'playlist_count': 31,
441 }, {
442 # available without pluralsight account
443 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
444 'only_matching': True,
445 }, {
446 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
447 'only_matching': True,
448 }]
449
450 def _real_extract(self, url):
451 course_id = self._match_id(url)
452
453 # TODO: PSM cookie
454
455 course = self._download_course(course_id, url, course_id)
456
457 title = course['title']
458 course_name = course['name']
459 course_data = course['modules']
460 description = course.get('description') or course.get('shortDescription')
461
462 entries = []
463 for num, module in enumerate(course_data, 1):
464 author = module.get('author')
465 module_name = module.get('name')
466 if not author or not module_name:
467 continue
468 for clip in module.get('clips', []):
469 clip_index = int_or_none(clip.get('index'))
470 if clip_index is None:
471 continue
472 clip_url = update_url_query(
473 '%s/player' % self._API_BASE, query={
474 'mode': 'live',
475 'course': course_name,
476 'author': author,
477 'name': module_name,
478 'clip': clip_index,
479 })
480 entries.append({
481 '_type': 'url_transparent',
482 'url': clip_url,
483 'ie_key': PluralsightIE.ie_key(),
484 'chapter': module.get('title'),
485 'chapter_number': num,
486 'chapter_id': module.get('moduleRef'),
487 })
488
489 return self.playlist_result(entries, course_id, title, description)