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