]>
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 | |
93d0583e S |
30 | def _download_course(self, course_id, url, display_id): |
31 | try: | |
32 | return self._download_course_rpc(course_id, url, display_id) | |
33 | except ExtractorError: | |
34 | # Old API fallback | |
35 | return self._download_json( | |
36 | 'https://app.pluralsight.com/player/user/api/v1/player/payload', | |
37 | display_id, data=urlencode_postdata({'courseId': course_id}), | |
38 | headers={'Referer': url}) | |
39 | ||
40 | def _download_course_rpc(self, course_id, url, display_id): | |
41 | response = self._download_json( | |
42 | '%s/player/functions/rpc' % self._API_BASE, display_id, | |
43 | 'Downloading course JSON', | |
44 | data=json.dumps({ | |
45 | 'fn': 'bootstrapPlayer', | |
46 | 'payload': { | |
47 | 'courseId': course_id, | |
48 | }, | |
49 | }).encode('utf-8'), | |
50 | headers={ | |
51 | 'Content-Type': 'application/json;charset=utf-8', | |
52 | 'Referer': url, | |
53 | }) | |
54 | ||
55 | course = try_get(response, lambda x: x['payload']['course'], dict) | |
56 | if course: | |
57 | return course | |
58 | ||
59 | raise ExtractorError( | |
60 | '%s said: %s' % (self.IE_NAME, response['error']['message']), | |
61 | expected=True) | |
62 | ||
563772ed S |
63 | |
64 | class PluralsightIE(PluralsightBaseIE): | |
483fc223 | 65 | IE_NAME = 'pluralsight' |
b0dfcab6 | 66 | _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?' |
c3a227d1 | 67 | _LOGIN_URL = 'https://app.pluralsight.com/id/' |
563772ed | 68 | |
483fc223 S |
69 | _NETRC_MACHINE = 'pluralsight' |
70 | ||
71bd93b8 | 71 | _TESTS = [{ |
483fc223 S |
72 | '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', |
73 | 'md5': '4d458cf5cf4c593788672419a8dd4cf8', | |
74 | 'info_dict': { | |
75 | 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04', | |
76 | 'ext': 'mp4', | |
8e5a7c5e | 77 | 'title': 'Demo Monitoring', |
483fc223 S |
78 | 'duration': 338, |
79 | }, | |
80 | 'skip': 'Requires pluralsight account credentials', | |
71bd93b8 S |
81 | }, { |
82 | 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live', | |
83 | 'only_matching': True, | |
c23e2664 S |
84 | }, { |
85 | # available without pluralsight account | |
86 | 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started', | |
87 | 'only_matching': True, | |
b0dfcab6 S |
88 | }, { |
89 | 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0', | |
90 | 'only_matching': True, | |
71bd93b8 | 91 | }] |
483fc223 S |
92 | |
93 | def _real_initialize(self): | |
94 | self._login() | |
95 | ||
96 | def _login(self): | |
97 | (username, password) = self._get_login_info() | |
98 | if username is None: | |
c23e2664 | 99 | return |
483fc223 S |
100 | |
101 | login_page = self._download_webpage( | |
102 | self._LOGIN_URL, None, 'Downloading login page') | |
103 | ||
104 | login_form = self._hidden_inputs(login_page) | |
105 | ||
106 | login_form.update({ | |
244cd042 S |
107 | 'Username': username, |
108 | 'Password': password, | |
483fc223 S |
109 | }) |
110 | ||
111 | post_url = self._search_regex( | |
112 | r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page, | |
113 | 'post url', default=self._LOGIN_URL, group='url') | |
114 | ||
115 | if not post_url.startswith('http'): | |
116 | post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url) | |
117 | ||
483fc223 | 118 | response = self._download_webpage( |
e4d95865 | 119 | post_url, None, 'Logging in', |
30317f48 S |
120 | data=urlencode_postdata(login_form), |
121 | headers={'Content-Type': 'application/x-www-form-urlencoded'}) | |
483fc223 S |
122 | |
123 | error = self._search_regex( | |
124 | r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>', | |
125 | response, 'error message', default=None) | |
126 | if error: | |
127 | raise ExtractorError('Unable to login: %s' % error, expected=True) | |
128 | ||
7e508ff2 | 129 | if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')): |
9dd5408c S |
130 | BLOCKED = 'Your account has been blocked due to suspicious activity' |
131 | if BLOCKED in response: | |
132 | raise ExtractorError( | |
133 | 'Unable to login: %s' % BLOCKED, expected=True) | |
7e508ff2 S |
134 | raise ExtractorError('Unable to log in') |
135 | ||
8c3e35dd S |
136 | def _get_subtitles(self, author, clip_id, lang, name, duration, video_id): |
137 | captions_post = { | |
138 | 'a': author, | |
139 | 'cn': clip_id, | |
140 | 'lc': lang, | |
141 | 'm': name, | |
142 | } | |
143 | captions = self._download_json( | |
9df6b03c | 144 | '%s/player/retrieve-captions' % self._API_BASE, video_id, |
8c3e35dd S |
145 | 'Downloading captions JSON', 'Unable to download captions JSON', |
146 | fatal=False, data=json.dumps(captions_post).encode('utf-8'), | |
147 | headers={'Content-Type': 'application/json;charset=utf-8'}) | |
148 | if captions: | |
149 | return { | |
150 | lang: [{ | |
151 | 'ext': 'json', | |
152 | 'data': json.dumps(captions), | |
153 | }, { | |
154 | 'ext': 'srt', | |
155 | 'data': self._convert_subtitles(duration, captions), | |
156 | }] | |
157 | } | |
158 | ||
159 | @staticmethod | |
160 | def _convert_subtitles(duration, subs): | |
161 | srt = '' | |
425f3fdf S |
162 | TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset') |
163 | TEXT_KEYS = ('text', 'Text') | |
8c3e35dd S |
164 | for num, current in enumerate(subs): |
165 | current = subs[num] | |
425f3fdf S |
166 | start, text = ( |
167 | float_or_none(dict_get(current, TIME_OFFSET_KEYS)), | |
168 | dict_get(current, TEXT_KEYS)) | |
8c3e35dd S |
169 | if start is None or text is None: |
170 | continue | |
171 | end = duration if num == len(subs) - 1 else float_or_none( | |
425f3fdf | 172 | dict_get(subs[num + 1], TIME_OFFSET_KEYS)) |
30317f48 S |
173 | if end is None: |
174 | continue | |
8c3e35dd S |
175 | srt += os.linesep.join( |
176 | ( | |
177 | '%d' % num, | |
178 | '%s --> %s' % ( | |
179 | srt_subtitles_timecode(start), | |
180 | srt_subtitles_timecode(end)), | |
181 | text, | |
182 | os.linesep, | |
183 | )) | |
184 | return srt | |
185 | ||
483fc223 | 186 | def _real_extract(self, url): |
71bd93b8 S |
187 | qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query) |
188 | ||
189 | author = qs.get('author', [None])[0] | |
190 | name = qs.get('name', [None])[0] | |
191 | clip_id = qs.get('clip', [None])[0] | |
9df6b03c | 192 | course_name = qs.get('course', [None])[0] |
71bd93b8 | 193 | |
9df6b03c | 194 | if any(not f for f in (author, name, clip_id, course_name,)): |
71bd93b8 | 195 | raise ExtractorError('Invalid URL', expected=True) |
483fc223 S |
196 | |
197 | display_id = '%s-%s' % (name, clip_id) | |
198 | ||
93d0583e | 199 | course = self._download_course(course_name, url, display_id) |
9df6b03c S |
200 | |
201 | collection = course['modules'] | |
483fc223 | 202 | |
d212c93d | 203 | clip = None |
483fc223 S |
204 | |
205 | for module_ in collection: | |
02f0da20 | 206 | if name in (module_.get('moduleName'), module_.get('name')): |
483fc223 S |
207 | for clip_ in module_.get('clips', []): |
208 | clip_index = clip_.get('clipIndex') | |
02f0da20 S |
209 | if clip_index is None: |
210 | clip_index = clip_.get('index') | |
483fc223 S |
211 | if clip_index is None: |
212 | continue | |
213 | if compat_str(clip_index) == clip_id: | |
214 | clip = clip_ | |
215 | break | |
216 | ||
217 | if not clip: | |
218 | raise ExtractorError('Unable to resolve clip') | |
219 | ||
8e5a7c5e | 220 | title = clip['title'] |
8c3e35dd | 221 | |
483fc223 S |
222 | QUALITIES = { |
223 | 'low': {'width': 640, 'height': 480}, | |
224 | 'medium': {'width': 848, 'height': 640}, | |
225 | 'high': {'width': 1024, 'height': 768}, | |
756926ff | 226 | 'high-widescreen': {'width': 1280, 'height': 720}, |
483fc223 S |
227 | } |
228 | ||
756926ff S |
229 | QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',) |
230 | quality_key = qualities(QUALITIES_PREFERENCE) | |
231 | ||
4c57b485 S |
232 | AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities']) |
233 | ||
483fc223 | 234 | ALLOWED_QUALITIES = ( |
756926ff S |
235 | AllowedQuality('webm', ['high', ]), |
236 | AllowedQuality('mp4', ['low', 'medium', 'high', ]), | |
483fc223 S |
237 | ) |
238 | ||
756926ff S |
239 | # Some courses also offer widescreen resolution for high quality (see |
240 | # https://github.com/rg3/youtube-dl/issues/7766) | |
9df6b03c | 241 | widescreen = course.get('supportsWideScreenVideoFormats') is True |
756926ff S |
242 | best_quality = 'high-widescreen' if widescreen else 'high' |
243 | if widescreen: | |
244 | for allowed_quality in ALLOWED_QUALITIES: | |
245 | allowed_quality.qualities.append(best_quality) | |
246 | ||
cf186b77 S |
247 | # In order to minimize the number of calls to ViewClip API and reduce |
248 | # the probability of being throttled or banned by Pluralsight we will request | |
0eebf34d | 249 | # only single format until formats listing was explicitly requested. |
4c57b485 S |
250 | if self._downloader.params.get('listformats', False): |
251 | allowed_qualities = ALLOWED_QUALITIES | |
252 | else: | |
253 | def guess_allowed_qualities(): | |
254 | req_format = self._downloader.params.get('format') or 'best' | |
edc70f4a | 255 | req_format_split = req_format.split('-', 1) |
4c57b485 S |
256 | if len(req_format_split) > 1: |
257 | req_ext, req_quality = req_format_split | |
fac188c6 | 258 | req_quality = '-'.join(req_quality.split('-')[:2]) |
4c57b485 S |
259 | for allowed_quality in ALLOWED_QUALITIES: |
260 | if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities: | |
261 | return (AllowedQuality(req_ext, (req_quality, )), ) | |
262 | req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4' | |
756926ff | 263 | return (AllowedQuality(req_ext, (best_quality, )), ) |
4c57b485 S |
264 | allowed_qualities = guess_allowed_qualities() |
265 | ||
483fc223 | 266 | formats = [] |
756926ff S |
267 | for ext, qualities_ in allowed_qualities: |
268 | for quality in qualities_: | |
483fc223 S |
269 | f = QUALITIES[quality].copy() |
270 | clip_post = { | |
9df6b03c S |
271 | 'author': author, |
272 | 'includeCaptions': False, | |
273 | 'clipIndex': int(clip_id), | |
274 | 'courseName': course_name, | |
275 | 'locale': 'en', | |
276 | 'moduleName': name, | |
277 | 'mediaType': ext, | |
278 | 'quality': '%dx%d' % (f['width'], f['height']), | |
483fc223 | 279 | } |
483fc223 | 280 | format_id = '%s-%s' % (ext, quality) |
f8ae2c7f | 281 | viewclip = self._download_json( |
9df6b03c | 282 | '%s/video/clips/viewclip' % self._API_BASE, display_id, |
f8ae2c7f | 283 | 'Downloading %s viewclip JSON' % format_id, fatal=False, |
30317f48 S |
284 | data=json.dumps(clip_post).encode('utf-8'), |
285 | headers={'Content-Type': 'application/json;charset=utf-8'}) | |
38eb2968 S |
286 | |
287 | # Pluralsight tracks multiple sequential calls to ViewClip API and start | |
288 | # to return 429 HTTP errors after some time (see | |
289 | # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead | |
290 | # to account ban (see https://github.com/rg3/youtube-dl/issues/6842). | |
291 | # To somewhat reduce the probability of these consequences | |
292 | # we will sleep random amount of time before each call to ViewClip. | |
293 | self._sleep( | |
294 | random.randint(2, 5), display_id, | |
295 | '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling') | |
296 | ||
f8ae2c7f | 297 | if not viewclip: |
483fc223 | 298 | continue |
f8ae2c7f S |
299 | |
300 | clip_urls = viewclip.get('urls') | |
301 | if not isinstance(clip_urls, list): | |
302 | continue | |
303 | ||
304 | for clip_url_data in clip_urls: | |
305 | clip_url = clip_url_data.get('url') | |
306 | if not clip_url: | |
307 | continue | |
308 | cdn = clip_url_data.get('cdn') | |
309 | clip_f = f.copy() | |
310 | clip_f.update({ | |
311 | 'url': clip_url, | |
312 | 'ext': ext, | |
313 | 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id, | |
314 | 'quality': quality_key(quality), | |
315 | 'source_preference': int_or_none(clip_url_data.get('rank')), | |
316 | }) | |
317 | formats.append(clip_f) | |
318 | ||
483fc223 S |
319 | self._sort_formats(formats) |
320 | ||
8c3e35dd S |
321 | duration = int_or_none( |
322 | clip.get('duration')) or parse_duration(clip.get('formattedDuration')) | |
323 | ||
324 | # TODO: other languages? | |
325 | subtitles = self.extract_subtitles( | |
326 | author, clip_id, 'en', name, duration, display_id) | |
483fc223 S |
327 | |
328 | return { | |
bc0550c2 | 329 | 'id': clip.get('clipName') or clip['name'], |
8c3e35dd S |
330 | 'title': title, |
331 | 'duration': duration, | |
483fc223 | 332 | 'creator': author, |
8c3e35dd S |
333 | 'formats': formats, |
334 | 'subtitles': subtitles, | |
483fc223 S |
335 | } |
336 | ||
337 | ||
563772ed | 338 | class PluralsightCourseIE(PluralsightBaseIE): |
483fc223 | 339 | IE_NAME = 'pluralsight:course' |
a5cd0eb8 | 340 | _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)' |
c23e2664 | 341 | _TESTS = [{ |
483fc223 S |
342 | # Free course from Pluralsight Starter Subscription for Microsoft TechNet |
343 | # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz | |
344 | 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas', | |
345 | 'info_dict': { | |
346 | 'id': 'hosting-sql-server-windows-azure-iaas', | |
347 | 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals', | |
348 | 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986', | |
349 | }, | |
350 | 'playlist_count': 31, | |
c23e2664 S |
351 | }, { |
352 | # available without pluralsight account | |
353 | 'url': 'https://www.pluralsight.com/courses/angularjs-get-started', | |
354 | 'only_matching': True, | |
a5cd0eb8 S |
355 | }, { |
356 | 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents', | |
357 | 'only_matching': True, | |
c23e2664 | 358 | }] |
483fc223 S |
359 | |
360 | def _real_extract(self, url): | |
361 | course_id = self._match_id(url) | |
362 | ||
2b6bda1e S |
363 | # TODO: PSM cookie |
364 | ||
93d0583e | 365 | course = self._download_course(course_id, url, course_id) |
483fc223 S |
366 | |
367 | title = course['title'] | |
3d7e3aaa S |
368 | course_name = course['name'] |
369 | course_data = course['modules'] | |
483fc223 S |
370 | description = course.get('description') or course.get('shortDescription') |
371 | ||
483fc223 | 372 | entries = [] |
8018028d | 373 | for num, module in enumerate(course_data, 1): |
3d7e3aaa S |
374 | author = module.get('author') |
375 | module_name = module.get('name') | |
376 | if not author or not module_name: | |
377 | continue | |
483fc223 | 378 | for clip in module.get('clips', []): |
3d7e3aaa S |
379 | clip_index = int_or_none(clip.get('index')) |
380 | if clip_index is None: | |
483fc223 | 381 | continue |
3d7e3aaa S |
382 | clip_url = update_url_query( |
383 | '%s/player' % self._API_BASE, query={ | |
384 | 'mode': 'live', | |
385 | 'course': course_name, | |
386 | 'author': author, | |
387 | 'name': module_name, | |
388 | 'clip': clip_index, | |
389 | }) | |
8018028d S |
390 | entries.append({ |
391 | '_type': 'url_transparent', | |
3d7e3aaa | 392 | 'url': clip_url, |
8018028d S |
393 | 'ie_key': PluralsightIE.ie_key(), |
394 | 'chapter': module.get('title'), | |
395 | 'chapter_number': num, | |
396 | 'chapter_id': module.get('moduleRef'), | |
397 | }) | |
483fc223 | 398 | |
483fc223 | 399 | return self.playlist_result(entries, course_id, title, description) |