]>
Commit | Line | Data |
---|---|---|
483fc223 S |
1 | from __future__ import unicode_literals |
2 | ||
8c3e35dd | 3 | import collections |
483fc223 | 4 | import json |
8c3e35dd | 5 | import os |
38eb2968 | 6 | import random |
483fc223 S |
7 | |
8 | from .common import InfoExtractor | |
9 | from ..compat import ( | |
10 | compat_str, | |
483fc223 S |
11 | compat_urlparse, |
12 | ) | |
13 | from ..utils import ( | |
425f3fdf | 14 | dict_get, |
483fc223 | 15 | ExtractorError, |
8c3e35dd | 16 | float_or_none, |
483fc223 S |
17 | int_or_none, |
18 | parse_duration, | |
756926ff | 19 | qualities, |
8c3e35dd | 20 | srt_subtitles_timecode, |
93d0583e | 21 | try_get, |
3d7e3aaa | 22 | update_url_query, |
6e6bc8da | 23 | urlencode_postdata, |
483fc223 S |
24 | ) |
25 | ||
26 | ||
563772ed | 27 | class PluralsightBaseIE(InfoExtractor): |
9df6b03c | 28 | _API_BASE = 'https://app.pluralsight.com' |
563772ed | 29 | |
836ef484 S |
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 | ||
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 | ||
93d0583e S |
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( | |
836ef484 S |
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) | |
93d0583e S |
104 | if course: |
105 | return course | |
106 | ||
107 | raise ExtractorError( | |
108 | '%s said: %s' % (self.IE_NAME, response['error']['message']), | |
109 | expected=True) | |
110 | ||
563772ed S |
111 | |
112 | class PluralsightIE(PluralsightBaseIE): | |
483fc223 | 113 | IE_NAME = 'pluralsight' |
b0dfcab6 | 114 | _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?' |
c3a227d1 | 115 | _LOGIN_URL = 'https://app.pluralsight.com/id/' |
563772ed | 116 | |
483fc223 S |
117 | _NETRC_MACHINE = 'pluralsight' |
118 | ||
71bd93b8 | 119 | _TESTS = [{ |
483fc223 S |
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', | |
8e5a7c5e | 125 | 'title': 'Demo Monitoring', |
483fc223 S |
126 | 'duration': 338, |
127 | }, | |
128 | 'skip': 'Requires pluralsight account credentials', | |
71bd93b8 S |
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, | |
c23e2664 S |
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, | |
b0dfcab6 S |
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, | |
71bd93b8 | 139 | }] |
483fc223 | 140 | |
836ef484 S |
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 | ||
483fc223 S |
163 | def _real_initialize(self): |
164 | self._login() | |
165 | ||
166 | def _login(self): | |
68217024 | 167 | username, password = self._get_login_info() |
483fc223 | 168 | if username is None: |
c23e2664 | 169 | return |
483fc223 S |
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({ | |
244cd042 S |
177 | 'Username': username, |
178 | 'Password': password, | |
483fc223 S |
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 | ||
483fc223 | 188 | response = self._download_webpage( |
e4d95865 | 189 | post_url, None, 'Logging in', |
30317f48 S |
190 | data=urlencode_postdata(login_form), |
191 | headers={'Content-Type': 'application/x-www-form-urlencoded'}) | |
483fc223 S |
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 | ||
7e508ff2 | 199 | if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')): |
9dd5408c S |
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) | |
c94427dd S |
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 | ||
7e508ff2 S |
211 | raise ExtractorError('Unable to log in') |
212 | ||
a3f86160 | 213 | def _get_subtitles(self, author, clip_idx, lang, name, duration, video_id): |
8c3e35dd S |
214 | captions_post = { |
215 | 'a': author, | |
c17e100b | 216 | 'cn': int(clip_idx), |
8c3e35dd S |
217 | 'lc': lang, |
218 | 'm': name, | |
219 | } | |
220 | captions = self._download_json( | |
9df6b03c | 221 | '%s/player/retrieve-captions' % self._API_BASE, video_id, |
8c3e35dd S |
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 = '' | |
425f3fdf S |
239 | TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset') |
240 | TEXT_KEYS = ('text', 'Text') | |
8c3e35dd S |
241 | for num, current in enumerate(subs): |
242 | current = subs[num] | |
425f3fdf | 243 | start, text = ( |
2c8e11b4 | 244 | float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)), |
425f3fdf | 245 | dict_get(current, TEXT_KEYS)) |
8c3e35dd S |
246 | if start is None or text is None: |
247 | continue | |
248 | end = duration if num == len(subs) - 1 else float_or_none( | |
2c8e11b4 | 249 | dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False)) |
30317f48 S |
250 | if end is None: |
251 | continue | |
8c3e35dd S |
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 | ||
483fc223 | 263 | def _real_extract(self, url): |
71bd93b8 S |
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] | |
a3f86160 | 268 | clip_idx = qs.get('clip', [None])[0] |
9df6b03c | 269 | course_name = qs.get('course', [None])[0] |
71bd93b8 | 270 | |
a3f86160 | 271 | if any(not f for f in (author, name, clip_idx, course_name,)): |
71bd93b8 | 272 | raise ExtractorError('Invalid URL', expected=True) |
483fc223 | 273 | |
a3f86160 | 274 | display_id = '%s-%s' % (name, clip_idx) |
483fc223 | 275 | |
93d0583e | 276 | course = self._download_course(course_name, url, display_id) |
9df6b03c S |
277 | |
278 | collection = course['modules'] | |
483fc223 | 279 | |
d212c93d | 280 | clip = None |
483fc223 S |
281 | |
282 | for module_ in collection: | |
02f0da20 | 283 | if name in (module_.get('moduleName'), module_.get('name')): |
483fc223 S |
284 | for clip_ in module_.get('clips', []): |
285 | clip_index = clip_.get('clipIndex') | |
02f0da20 S |
286 | if clip_index is None: |
287 | clip_index = clip_.get('index') | |
483fc223 S |
288 | if clip_index is None: |
289 | continue | |
a3f86160 | 290 | if compat_str(clip_index) == clip_idx: |
483fc223 S |
291 | clip = clip_ |
292 | break | |
293 | ||
294 | if not clip: | |
295 | raise ExtractorError('Unable to resolve clip') | |
296 | ||
8e5a7c5e | 297 | title = clip['title'] |
a3f86160 | 298 | clip_id = clip.get('clipName') or clip.get('name') or clip['clipId'] |
8c3e35dd | 299 | |
483fc223 S |
300 | QUALITIES = { |
301 | 'low': {'width': 640, 'height': 480}, | |
302 | 'medium': {'width': 848, 'height': 640}, | |
303 | 'high': {'width': 1024, 'height': 768}, | |
756926ff | 304 | 'high-widescreen': {'width': 1280, 'height': 720}, |
483fc223 S |
305 | } |
306 | ||
756926ff S |
307 | QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',) |
308 | quality_key = qualities(QUALITIES_PREFERENCE) | |
309 | ||
4c57b485 S |
310 | AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities']) |
311 | ||
483fc223 | 312 | ALLOWED_QUALITIES = ( |
756926ff S |
313 | AllowedQuality('webm', ['high', ]), |
314 | AllowedQuality('mp4', ['low', 'medium', 'high', ]), | |
483fc223 S |
315 | ) |
316 | ||
756926ff S |
317 | # Some courses also offer widescreen resolution for high quality (see |
318 | # https://github.com/rg3/youtube-dl/issues/7766) | |
9df6b03c | 319 | widescreen = course.get('supportsWideScreenVideoFormats') is True |
756926ff S |
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 | ||
cf186b77 S |
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 | |
0eebf34d | 327 | # only single format until formats listing was explicitly requested. |
4c57b485 S |
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' | |
edc70f4a | 333 | req_format_split = req_format.split('-', 1) |
4c57b485 S |
334 | if len(req_format_split) > 1: |
335 | req_ext, req_quality = req_format_split | |
fac188c6 | 336 | req_quality = '-'.join(req_quality.split('-')[:2]) |
4c57b485 S |
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' | |
756926ff | 341 | return (AllowedQuality(req_ext, (best_quality, )), ) |
4c57b485 S |
342 | allowed_qualities = guess_allowed_qualities() |
343 | ||
483fc223 | 344 | formats = [] |
756926ff S |
345 | for ext, qualities_ in allowed_qualities: |
346 | for quality in qualities_: | |
483fc223 S |
347 | f = QUALITIES[quality].copy() |
348 | clip_post = { | |
9df6b03c | 349 | 'author': author, |
836ef484 | 350 | 'includeCaptions': 'false', |
a3f86160 | 351 | 'clipIndex': int(clip_idx), |
9df6b03c S |
352 | 'courseName': course_name, |
353 | 'locale': 'en', | |
354 | 'moduleName': name, | |
355 | 'mediaType': ext, | |
356 | 'quality': '%dx%d' % (f['width'], f['height']), | |
483fc223 | 357 | } |
483fc223 | 358 | format_id = '%s-%s' % (ext, quality) |
836ef484 S |
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'}) | |
38eb2968 S |
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 | ||
f8ae2c7f | 387 | if not viewclip: |
483fc223 | 388 | continue |
f8ae2c7f S |
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 | ||
483fc223 S |
409 | self._sort_formats(formats) |
410 | ||
8c3e35dd S |
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( | |
a3f86160 | 416 | author, clip_idx, 'en', name, duration, display_id) |
483fc223 S |
417 | |
418 | return { | |
a3f86160 | 419 | 'id': clip_id, |
8c3e35dd S |
420 | 'title': title, |
421 | 'duration': duration, | |
483fc223 | 422 | 'creator': author, |
8c3e35dd S |
423 | 'formats': formats, |
424 | 'subtitles': subtitles, | |
483fc223 S |
425 | } |
426 | ||
427 | ||
563772ed | 428 | class PluralsightCourseIE(PluralsightBaseIE): |
483fc223 | 429 | IE_NAME = 'pluralsight:course' |
a5cd0eb8 | 430 | _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)' |
c23e2664 | 431 | _TESTS = [{ |
483fc223 S |
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, | |
c23e2664 S |
441 | }, { |
442 | # available without pluralsight account | |
443 | 'url': 'https://www.pluralsight.com/courses/angularjs-get-started', | |
444 | 'only_matching': True, | |
a5cd0eb8 S |
445 | }, { |
446 | 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents', | |
447 | 'only_matching': True, | |
c23e2664 | 448 | }] |
483fc223 S |
449 | |
450 | def _real_extract(self, url): | |
451 | course_id = self._match_id(url) | |
452 | ||
2b6bda1e S |
453 | # TODO: PSM cookie |
454 | ||
93d0583e | 455 | course = self._download_course(course_id, url, course_id) |
483fc223 S |
456 | |
457 | title = course['title'] | |
3d7e3aaa S |
458 | course_name = course['name'] |
459 | course_data = course['modules'] | |
483fc223 S |
460 | description = course.get('description') or course.get('shortDescription') |
461 | ||
483fc223 | 462 | entries = [] |
8018028d | 463 | for num, module in enumerate(course_data, 1): |
3d7e3aaa S |
464 | author = module.get('author') |
465 | module_name = module.get('name') | |
466 | if not author or not module_name: | |
467 | continue | |
483fc223 | 468 | for clip in module.get('clips', []): |
3d7e3aaa S |
469 | clip_index = int_or_none(clip.get('index')) |
470 | if clip_index is None: | |
483fc223 | 471 | continue |
3d7e3aaa S |
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 | }) | |
8018028d S |
480 | entries.append({ |
481 | '_type': 'url_transparent', | |
3d7e3aaa | 482 | 'url': clip_url, |
8018028d S |
483 | 'ie_key': PluralsightIE.ie_key(), |
484 | 'chapter': module.get('title'), | |
485 | 'chapter_number': num, | |
486 | 'chapter_id': module.get('moduleRef'), | |
487 | }) | |
483fc223 | 488 | |
483fc223 | 489 | return self.playlist_result(entries, course_id, title, description) |