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