[pluralsight] Modernize and make more robust
[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 import re
8
9 from .common import InfoExtractor
10 from ..compat import (
11     compat_str,
12     compat_urlparse,
13 )
14 from ..utils import (
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 = 'http://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
55     def _real_initialize(self):
56         self._login()
57
58     def _login(self):
59         (username, password) = self._get_login_info()
60         if username is None:
61             return
62
63         login_page = self._download_webpage(
64             self._LOGIN_URL, None, 'Downloading login page')
65
66         login_form = self._hidden_inputs(login_page)
67
68         login_form.update({
69             'Username': username,
70             'Password': password,
71         })
72
73         post_url = self._search_regex(
74             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
75             'post url', default=self._LOGIN_URL, group='url')
76
77         if not post_url.startswith('http'):
78             post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
79
80         response = self._download_webpage(
81             post_url, None, 'Logging in as %s' % username,
82             data=urlencode_postdata(login_form),
83             headers={'Content-Type': 'application/x-www-form-urlencoded'})
84
85         error = self._search_regex(
86             r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
87             response, 'error message', default=None)
88         if error:
89             raise ExtractorError('Unable to login: %s' % error, expected=True)
90
91         if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
92             raise ExtractorError('Unable to log in')
93
94     def _get_subtitles(self, author, clip_id, lang, name, duration, video_id):
95         captions_post = {
96             'a': author,
97             'cn': clip_id,
98             'lc': lang,
99             'm': name,
100         }
101         captions = self._download_json(
102             '%s/training/Player/Captions' % self._API_BASE, video_id,
103             'Downloading captions JSON', 'Unable to download captions JSON',
104             fatal=False, data=json.dumps(captions_post).encode('utf-8'),
105             headers={'Content-Type': 'application/json;charset=utf-8'})
106         if captions:
107             return {
108                 lang: [{
109                     'ext': 'json',
110                     'data': json.dumps(captions),
111                 }, {
112                     'ext': 'srt',
113                     'data': self._convert_subtitles(duration, captions),
114                 }]
115             }
116
117     @staticmethod
118     def _convert_subtitles(duration, subs):
119         srt = ''
120         for num, current in enumerate(subs):
121             current = subs[num]
122             start, text = float_or_none(
123                 current.get('DisplayTimeOffset')), current.get('Text')
124             if start is None or text is None:
125                 continue
126             end = duration if num == len(subs) - 1 else float_or_none(
127                 subs[num + 1].get('DisplayTimeOffset'))
128             if end is None:
129                 continue
130             srt += os.linesep.join(
131                 (
132                     '%d' % num,
133                     '%s --> %s' % (
134                         srt_subtitles_timecode(start),
135                         srt_subtitles_timecode(end)),
136                     text,
137                     os.linesep,
138                 ))
139         return srt
140
141     def _real_extract(self, url):
142         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
143
144         author = qs.get('author', [None])[0]
145         name = qs.get('name', [None])[0]
146         clip_id = qs.get('clip', [None])[0]
147         course = qs.get('course', [None])[0]
148
149         if any(not f for f in (author, name, clip_id, course,)):
150             raise ExtractorError('Invalid URL', expected=True)
151
152         display_id = '%s-%s' % (name, clip_id)
153
154         webpage = self._download_webpage(url, display_id)
155
156         modules = self._search_regex(
157             r'moduleCollection\s*:\s*new\s+ModuleCollection\((\[.+?\])\s*,\s*\$rootScope\)',
158             webpage, 'modules', default=None)
159
160         if modules:
161             collection = self._parse_json(modules, display_id)
162         else:
163             # Webpage may be served in different layout (see
164             # https://github.com/rg3/youtube-dl/issues/7607)
165             collection = self._parse_json(
166                 self._search_regex(
167                     r'var\s+initialState\s*=\s*({.+?});\n', webpage, 'initial state'),
168                 display_id)['course']['modules']
169
170         module, clip = None, None
171
172         for module_ in collection:
173             if name in (module_.get('moduleName'), module_.get('name')):
174                 module = module_
175                 for clip_ in module_.get('clips', []):
176                     clip_index = clip_.get('clipIndex')
177                     if clip_index is None:
178                         clip_index = clip_.get('index')
179                     if clip_index is None:
180                         continue
181                     if compat_str(clip_index) == clip_id:
182                         clip = clip_
183                         break
184
185         if not clip:
186             raise ExtractorError('Unable to resolve clip')
187
188         title = '%s - %s' % (module['title'], clip['title'])
189
190         QUALITIES = {
191             'low': {'width': 640, 'height': 480},
192             'medium': {'width': 848, 'height': 640},
193             'high': {'width': 1024, 'height': 768},
194             'high-widescreen': {'width': 1280, 'height': 720},
195         }
196
197         QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
198         quality_key = qualities(QUALITIES_PREFERENCE)
199
200         AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
201
202         ALLOWED_QUALITIES = (
203             AllowedQuality('webm', ['high', ]),
204             AllowedQuality('mp4', ['low', 'medium', 'high', ]),
205         )
206
207         # Some courses also offer widescreen resolution for high quality (see
208         # https://github.com/rg3/youtube-dl/issues/7766)
209         widescreen = True if re.search(
210             r'courseSupportsWidescreenVideoFormats\s*:\s*true', webpage) else False
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                     'a': author,
240                     'cap': 'false',
241                     'cn': clip_id,
242                     'course': course,
243                     'lc': 'en',
244                     'm': name,
245                     'mt': ext,
246                     'q': '%dx%d' % (f['width'], f['height']),
247                 }
248                 format_id = '%s-%s' % (ext, quality)
249                 clip_url = self._download_webpage(
250                     '%s/training/Player/ViewClip' % self._API_BASE, display_id,
251                     'Downloading %s URL' % 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 clip_url:
266                     continue
267                 f.update({
268                     'url': clip_url,
269                     'ext': ext,
270                     'format_id': format_id,
271                     'quality': quality_key(quality),
272                 })
273                 formats.append(f)
274         self._sort_formats(formats)
275
276         duration = int_or_none(
277             clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
278
279         # TODO: other languages?
280         subtitles = self.extract_subtitles(
281             author, clip_id, 'en', name, duration, display_id)
282
283         return {
284             'id': clip.get('clipName') or clip['name'],
285             'title': title,
286             'duration': duration,
287             'creator': author,
288             'formats': formats,
289             'subtitles': subtitles,
290         }
291
292
293 class PluralsightCourseIE(PluralsightBaseIE):
294     IE_NAME = 'pluralsight:course'
295     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
296     _TESTS = [{
297         # Free course from Pluralsight Starter Subscription for Microsoft TechNet
298         # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
299         'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
300         'info_dict': {
301             'id': 'hosting-sql-server-windows-azure-iaas',
302             'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
303             'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
304         },
305         'playlist_count': 31,
306     }, {
307         # available without pluralsight account
308         'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
309         'only_matching': True,
310     }, {
311         'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
312         'only_matching': True,
313     }]
314
315     def _real_extract(self, url):
316         course_id = self._match_id(url)
317
318         # TODO: PSM cookie
319
320         course = self._download_json(
321             '%s/data/course/%s' % (self._API_BASE, course_id),
322             course_id, 'Downloading course JSON')
323
324         title = course['title']
325         description = course.get('description') or course.get('shortDescription')
326
327         course_data = self._download_json(
328             '%s/data/course/content/%s' % (self._API_BASE, course_id),
329             course_id, 'Downloading course data JSON')
330
331         entries = []
332         for num, module in enumerate(course_data, 1):
333             for clip in module.get('clips', []):
334                 player_parameters = clip.get('playerParameters')
335                 if not player_parameters:
336                     continue
337                 entries.append({
338                     '_type': 'url_transparent',
339                     'url': '%s/training/player?%s' % (self._API_BASE, player_parameters),
340                     'ie_key': PluralsightIE.ie_key(),
341                     'chapter': module.get('title'),
342                     'chapter_number': num,
343                     'chapter_id': module.get('moduleRef'),
344                 })
345
346         return self.playlist_result(entries, course_id, title, description)