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