[pluralsight] Add support for subtitles (Closes #9681)
[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     sanitized_Request,
21     srt_subtitles_timecode,
22     urlencode_postdata,
23 )
24
25
26 class PluralsightBaseIE(InfoExtractor):
27     _API_BASE = 'http://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
56     def _real_initialize(self):
57         self._login()
58
59     def _login(self):
60         (username, password) = self._get_login_info()
61         if username is None:
62             return
63
64         login_page = self._download_webpage(
65             self._LOGIN_URL, None, 'Downloading login page')
66
67         login_form = self._hidden_inputs(login_page)
68
69         login_form.update({
70             'Username': username,
71             'Password': password,
72         })
73
74         post_url = self._search_regex(
75             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
76             'post url', default=self._LOGIN_URL, group='url')
77
78         if not post_url.startswith('http'):
79             post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
80
81         request = sanitized_Request(
82             post_url, urlencode_postdata(login_form))
83         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
84
85         response = self._download_webpage(
86             request, None, 'Logging in as %s' % username)
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/training/Player/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         for num, current in enumerate(subs):
124             current = subs[num]
125             start, text = float_or_none(
126                 current.get('DisplayTimeOffset')), current.get('Text')
127             if start is None or text is None:
128                 continue
129             end = duration if num == len(subs) - 1 else float_or_none(
130                 subs[num + 1].get('DisplayTimeOffset'))
131             srt += os.linesep.join(
132                 (
133                     '%d' % num,
134                     '%s --> %s' % (
135                         srt_subtitles_timecode(start),
136                         srt_subtitles_timecode(end)),
137                     text,
138                     os.linesep,
139                 ))
140         return srt
141
142     def _real_extract(self, url):
143         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
144
145         author = qs.get('author', [None])[0]
146         name = qs.get('name', [None])[0]
147         clip_id = qs.get('clip', [None])[0]
148         course = qs.get('course', [None])[0]
149
150         if any(not f for f in (author, name, clip_id, course,)):
151             raise ExtractorError('Invalid URL', expected=True)
152
153         display_id = '%s-%s' % (name, clip_id)
154
155         webpage = self._download_webpage(url, display_id)
156
157         modules = self._search_regex(
158             r'moduleCollection\s*:\s*new\s+ModuleCollection\((\[.+?\])\s*,\s*\$rootScope\)',
159             webpage, 'modules', default=None)
160
161         if modules:
162             collection = self._parse_json(modules, display_id)
163         else:
164             # Webpage may be served in different layout (see
165             # https://github.com/rg3/youtube-dl/issues/7607)
166             collection = self._parse_json(
167                 self._search_regex(
168                     r'var\s+initialState\s*=\s*({.+?});\n', webpage, 'initial state'),
169                 display_id)['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 = True if re.search(
211             r'courseSupportsWidescreenVideoFormats\s*:\s*true', webpage) else False
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                     'a': author,
241                     'cap': 'false',
242                     'cn': clip_id,
243                     'course': course,
244                     'lc': 'en',
245                     'm': name,
246                     'mt': ext,
247                     'q': '%dx%d' % (f['width'], f['height']),
248                 }
249                 request = sanitized_Request(
250                     '%s/training/Player/ViewClip' % self._API_BASE,
251                     json.dumps(clip_post).encode('utf-8'))
252                 request.add_header('Content-Type', 'application/json;charset=utf-8')
253                 format_id = '%s-%s' % (ext, quality)
254                 clip_url = self._download_webpage(
255                     request, display_id, 'Downloading %s URL' % format_id, fatal=False)
256
257                 # Pluralsight tracks multiple sequential calls to ViewClip API and start
258                 # to return 429 HTTP errors after some time (see
259                 # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
260                 # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
261                 # To somewhat reduce the probability of these consequences
262                 # we will sleep random amount of time before each call to ViewClip.
263                 self._sleep(
264                     random.randint(2, 5), display_id,
265                     '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
266
267                 if not clip_url:
268                     continue
269                 f.update({
270                     'url': clip_url,
271                     'ext': ext,
272                     'format_id': format_id,
273                     'quality': quality_key(quality),
274                 })
275                 formats.append(f)
276         self._sort_formats(formats)
277
278         duration = int_or_none(
279             clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
280
281         # TODO: other languages?
282         subtitles = self.extract_subtitles(
283             author, clip_id, 'en', name, duration, display_id)
284
285         return {
286             'id': clip.get('clipName') or clip['name'],
287             'title': title,
288             'duration': duration,
289             'creator': author,
290             'formats': formats,
291             'subtitles': subtitles,
292         }
293
294
295 class PluralsightCourseIE(PluralsightBaseIE):
296     IE_NAME = 'pluralsight:course'
297     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
298     _TESTS = [{
299         # Free course from Pluralsight Starter Subscription for Microsoft TechNet
300         # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
301         'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
302         'info_dict': {
303             'id': 'hosting-sql-server-windows-azure-iaas',
304             'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
305             'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
306         },
307         'playlist_count': 31,
308     }, {
309         # available without pluralsight account
310         'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
311         'only_matching': True,
312     }, {
313         'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
314         'only_matching': True,
315     }]
316
317     def _real_extract(self, url):
318         course_id = self._match_id(url)
319
320         # TODO: PSM cookie
321
322         course = self._download_json(
323             '%s/data/course/%s' % (self._API_BASE, course_id),
324             course_id, 'Downloading course JSON')
325
326         title = course['title']
327         description = course.get('description') or course.get('shortDescription')
328
329         course_data = self._download_json(
330             '%s/data/course/content/%s' % (self._API_BASE, course_id),
331             course_id, 'Downloading course data JSON')
332
333         entries = []
334         for num, module in enumerate(course_data, 1):
335             for clip in module.get('clips', []):
336                 player_parameters = clip.get('playerParameters')
337                 if not player_parameters:
338                     continue
339                 entries.append({
340                     '_type': 'url_transparent',
341                     'url': '%s/training/player?%s' % (self._API_BASE, player_parameters),
342                     'ie_key': PluralsightIE.ie_key(),
343                     'chapter': module.get('title'),
344                     'chapter_number': num,
345                     'chapter_id': module.get('moduleRef'),
346                 })
347
348         return self.playlist_result(entries, course_id, title, description)