]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/pluralsight.py
Add missing python3-setuptools build dependency. closes: #902279.
[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 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
63
64 class PluralsightIE(PluralsightBaseIE):
65 IE_NAME = 'pluralsight'
66 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
67 _LOGIN_URL = 'https://app.pluralsight.com/id/'
68
69 _NETRC_MACHINE = 'pluralsight'
70
71 _TESTS = [{
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',
77 'title': 'Demo Monitoring',
78 'duration': 338,
79 },
80 'skip': 'Requires pluralsight account credentials',
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,
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,
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,
91 }]
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:
99 return
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({
107 'Username': username,
108 'Password': password,
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
118 response = self._download_webpage(
119 post_url, None, 'Logging in',
120 data=urlencode_postdata(login_form),
121 headers={'Content-Type': 'application/x-www-form-urlencoded'})
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
129 if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
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)
134 MUST_AGREE = 'To continue using Pluralsight, you must agree to'
135 if any(p in response for p in (MUST_AGREE, '>Disagree<', '>Agree<')):
136 raise ExtractorError(
137 'Unable to login: %s some documents. Go to pluralsight.com, '
138 'log in and agree with what Pluralsight requires.'
139 % MUST_AGREE, expected=True)
140
141 raise ExtractorError('Unable to log in')
142
143 def _get_subtitles(self, author, clip_idx, lang, name, duration, video_id):
144 captions_post = {
145 'a': author,
146 'cn': clip_idx,
147 'lc': lang,
148 'm': name,
149 }
150 captions = self._download_json(
151 '%s/player/retrieve-captions' % self._API_BASE, video_id,
152 'Downloading captions JSON', 'Unable to download captions JSON',
153 fatal=False, data=json.dumps(captions_post).encode('utf-8'),
154 headers={'Content-Type': 'application/json;charset=utf-8'})
155 if captions:
156 return {
157 lang: [{
158 'ext': 'json',
159 'data': json.dumps(captions),
160 }, {
161 'ext': 'srt',
162 'data': self._convert_subtitles(duration, captions),
163 }]
164 }
165
166 @staticmethod
167 def _convert_subtitles(duration, subs):
168 srt = ''
169 TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
170 TEXT_KEYS = ('text', 'Text')
171 for num, current in enumerate(subs):
172 current = subs[num]
173 start, text = (
174 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
175 dict_get(current, TEXT_KEYS))
176 if start is None or text is None:
177 continue
178 end = duration if num == len(subs) - 1 else float_or_none(
179 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
180 if end is None:
181 continue
182 srt += os.linesep.join(
183 (
184 '%d' % num,
185 '%s --> %s' % (
186 srt_subtitles_timecode(start),
187 srt_subtitles_timecode(end)),
188 text,
189 os.linesep,
190 ))
191 return srt
192
193 def _real_extract(self, url):
194 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
195
196 author = qs.get('author', [None])[0]
197 name = qs.get('name', [None])[0]
198 clip_idx = qs.get('clip', [None])[0]
199 course_name = qs.get('course', [None])[0]
200
201 if any(not f for f in (author, name, clip_idx, course_name,)):
202 raise ExtractorError('Invalid URL', expected=True)
203
204 display_id = '%s-%s' % (name, clip_idx)
205
206 course = self._download_course(course_name, url, display_id)
207
208 collection = course['modules']
209
210 clip = None
211
212 for module_ in collection:
213 if name in (module_.get('moduleName'), module_.get('name')):
214 for clip_ in module_.get('clips', []):
215 clip_index = clip_.get('clipIndex')
216 if clip_index is None:
217 clip_index = clip_.get('index')
218 if clip_index is None:
219 continue
220 if compat_str(clip_index) == clip_idx:
221 clip = clip_
222 break
223
224 if not clip:
225 raise ExtractorError('Unable to resolve clip')
226
227 title = clip['title']
228 clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
229
230 QUALITIES = {
231 'low': {'width': 640, 'height': 480},
232 'medium': {'width': 848, 'height': 640},
233 'high': {'width': 1024, 'height': 768},
234 'high-widescreen': {'width': 1280, 'height': 720},
235 }
236
237 QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
238 quality_key = qualities(QUALITIES_PREFERENCE)
239
240 AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
241
242 ALLOWED_QUALITIES = (
243 AllowedQuality('webm', ['high', ]),
244 AllowedQuality('mp4', ['low', 'medium', 'high', ]),
245 )
246
247 # Some courses also offer widescreen resolution for high quality (see
248 # https://github.com/rg3/youtube-dl/issues/7766)
249 widescreen = course.get('supportsWideScreenVideoFormats') is True
250 best_quality = 'high-widescreen' if widescreen else 'high'
251 if widescreen:
252 for allowed_quality in ALLOWED_QUALITIES:
253 allowed_quality.qualities.append(best_quality)
254
255 # In order to minimize the number of calls to ViewClip API and reduce
256 # the probability of being throttled or banned by Pluralsight we will request
257 # only single format until formats listing was explicitly requested.
258 if self._downloader.params.get('listformats', False):
259 allowed_qualities = ALLOWED_QUALITIES
260 else:
261 def guess_allowed_qualities():
262 req_format = self._downloader.params.get('format') or 'best'
263 req_format_split = req_format.split('-', 1)
264 if len(req_format_split) > 1:
265 req_ext, req_quality = req_format_split
266 req_quality = '-'.join(req_quality.split('-')[:2])
267 for allowed_quality in ALLOWED_QUALITIES:
268 if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
269 return (AllowedQuality(req_ext, (req_quality, )), )
270 req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
271 return (AllowedQuality(req_ext, (best_quality, )), )
272 allowed_qualities = guess_allowed_qualities()
273
274 formats = []
275 for ext, qualities_ in allowed_qualities:
276 for quality in qualities_:
277 f = QUALITIES[quality].copy()
278 clip_post = {
279 'author': author,
280 'includeCaptions': False,
281 'clipIndex': int(clip_idx),
282 'courseName': course_name,
283 'locale': 'en',
284 'moduleName': name,
285 'mediaType': ext,
286 'quality': '%dx%d' % (f['width'], f['height']),
287 }
288 format_id = '%s-%s' % (ext, quality)
289 viewclip = self._download_json(
290 '%s/video/clips/viewclip' % self._API_BASE, display_id,
291 'Downloading %s viewclip JSON' % format_id, fatal=False,
292 data=json.dumps(clip_post).encode('utf-8'),
293 headers={'Content-Type': 'application/json;charset=utf-8'})
294
295 # Pluralsight tracks multiple sequential calls to ViewClip API and start
296 # to return 429 HTTP errors after some time (see
297 # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
298 # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
299 # To somewhat reduce the probability of these consequences
300 # we will sleep random amount of time before each call to ViewClip.
301 self._sleep(
302 random.randint(2, 5), display_id,
303 '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
304
305 if not viewclip:
306 continue
307
308 clip_urls = viewclip.get('urls')
309 if not isinstance(clip_urls, list):
310 continue
311
312 for clip_url_data in clip_urls:
313 clip_url = clip_url_data.get('url')
314 if not clip_url:
315 continue
316 cdn = clip_url_data.get('cdn')
317 clip_f = f.copy()
318 clip_f.update({
319 'url': clip_url,
320 'ext': ext,
321 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
322 'quality': quality_key(quality),
323 'source_preference': int_or_none(clip_url_data.get('rank')),
324 })
325 formats.append(clip_f)
326
327 self._sort_formats(formats)
328
329 duration = int_or_none(
330 clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
331
332 # TODO: other languages?
333 subtitles = self.extract_subtitles(
334 author, clip_idx, 'en', name, duration, display_id)
335
336 return {
337 'id': clip_id,
338 'title': title,
339 'duration': duration,
340 'creator': author,
341 'formats': formats,
342 'subtitles': subtitles,
343 }
344
345
346 class PluralsightCourseIE(PluralsightBaseIE):
347 IE_NAME = 'pluralsight:course'
348 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
349 _TESTS = [{
350 # Free course from Pluralsight Starter Subscription for Microsoft TechNet
351 # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
352 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
353 'info_dict': {
354 'id': 'hosting-sql-server-windows-azure-iaas',
355 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
356 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
357 },
358 'playlist_count': 31,
359 }, {
360 # available without pluralsight account
361 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
362 'only_matching': True,
363 }, {
364 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
365 'only_matching': True,
366 }]
367
368 def _real_extract(self, url):
369 course_id = self._match_id(url)
370
371 # TODO: PSM cookie
372
373 course = self._download_course(course_id, url, course_id)
374
375 title = course['title']
376 course_name = course['name']
377 course_data = course['modules']
378 description = course.get('description') or course.get('shortDescription')
379
380 entries = []
381 for num, module in enumerate(course_data, 1):
382 author = module.get('author')
383 module_name = module.get('name')
384 if not author or not module_name:
385 continue
386 for clip in module.get('clips', []):
387 clip_index = int_or_none(clip.get('index'))
388 if clip_index is None:
389 continue
390 clip_url = update_url_query(
391 '%s/player' % self._API_BASE, query={
392 'mode': 'live',
393 'course': course_name,
394 'author': author,
395 'name': module_name,
396 'clip': clip_index,
397 })
398 entries.append({
399 '_type': 'url_transparent',
400 'url': clip_url,
401 'ie_key': PluralsightIE.ie_key(),
402 'chapter': module.get('title'),
403 'chapter_number': num,
404 'chapter_id': module.get('moduleRef'),
405 })
406
407 return self.playlist_result(entries, course_id, title, description)