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