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