Switch codebase to use sanitized_Request instead of
[youtube-dl] / youtube_dl / extractor / pluralsight.py
1 from __future__ import unicode_literals
2
3 import json
4 import random
5 import collections
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_str,
10     compat_urllib_parse,
11     compat_urlparse,
12 )
13 from ..utils import (
14     ExtractorError,
15     int_or_none,
16     parse_duration,
17     sanitized_Request,
18 )
19
20
21 class PluralsightBaseIE(InfoExtractor):
22     _API_BASE = 'http://app.pluralsight.com'
23
24
25 class PluralsightIE(PluralsightBaseIE):
26     IE_NAME = 'pluralsight'
27     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/training/player\?'
28     _LOGIN_URL = 'https://app.pluralsight.com/id/'
29
30     _NETRC_MACHINE = 'pluralsight'
31
32     _TESTS = [{
33         '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',
34         'md5': '4d458cf5cf4c593788672419a8dd4cf8',
35         'info_dict': {
36             'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
37             'ext': 'mp4',
38             'title': 'Management of SQL Server - Demo Monitoring',
39             'duration': 338,
40         },
41         'skip': 'Requires pluralsight account credentials',
42     }, {
43         'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
44         'only_matching': True,
45     }, {
46         # available without pluralsight account
47         'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
48         'only_matching': True,
49     }]
50
51     def _real_initialize(self):
52         self._login()
53
54     def _login(self):
55         (username, password) = self._get_login_info()
56         if username is None:
57             return
58
59         login_page = self._download_webpage(
60             self._LOGIN_URL, None, 'Downloading login page')
61
62         login_form = self._hidden_inputs(login_page)
63
64         login_form.update({
65             'Username': username.encode('utf-8'),
66             'Password': password.encode('utf-8'),
67         })
68
69         post_url = self._search_regex(
70             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
71             'post url', default=self._LOGIN_URL, group='url')
72
73         if not post_url.startswith('http'):
74             post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
75
76         request = sanitized_Request(
77             post_url, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
78         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
79
80         response = self._download_webpage(
81             request, None, 'Logging in as %s' % username)
82
83         error = self._search_regex(
84             r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
85             response, 'error message', default=None)
86         if error:
87             raise ExtractorError('Unable to login: %s' % error, expected=True)
88
89         if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
90             raise ExtractorError('Unable to log in')
91
92     def _real_extract(self, url):
93         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
94
95         author = qs.get('author', [None])[0]
96         name = qs.get('name', [None])[0]
97         clip_id = qs.get('clip', [None])[0]
98         course = qs.get('course', [None])[0]
99
100         if any(not f for f in (author, name, clip_id, course,)):
101             raise ExtractorError('Invalid URL', expected=True)
102
103         display_id = '%s-%s' % (name, clip_id)
104
105         webpage = self._download_webpage(url, display_id)
106
107         modules = self._search_regex(
108             r'moduleCollection\s*:\s*new\s+ModuleCollection\((\[.+?\])\s*,\s*\$rootScope\)',
109             webpage, 'modules', default=None)
110
111         if modules:
112             collection = self._parse_json(modules, display_id)
113         else:
114             # Webpage may be served in different layout (see
115             # https://github.com/rg3/youtube-dl/issues/7607)
116             collection = self._parse_json(
117                 self._search_regex(
118                     r'var\s+initialState\s*=\s*({.+?});\n', webpage, 'initial state'),
119                 display_id)['course']['modules']
120
121         module, clip = None, None
122
123         for module_ in collection:
124             if name in (module_.get('moduleName'), module_.get('name')):
125                 module = module_
126                 for clip_ in module_.get('clips', []):
127                     clip_index = clip_.get('clipIndex')
128                     if clip_index is None:
129                         clip_index = clip_.get('index')
130                     if clip_index is None:
131                         continue
132                     if compat_str(clip_index) == clip_id:
133                         clip = clip_
134                         break
135
136         if not clip:
137             raise ExtractorError('Unable to resolve clip')
138
139         QUALITIES = {
140             'low': {'width': 640, 'height': 480},
141             'medium': {'width': 848, 'height': 640},
142             'high': {'width': 1024, 'height': 768},
143         }
144
145         AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
146
147         ALLOWED_QUALITIES = (
148             AllowedQuality('webm', ('high',)),
149             AllowedQuality('mp4', ('low', 'medium', 'high',)),
150         )
151
152         # In order to minimize the number of calls to ViewClip API and reduce
153         # the probability of being throttled or banned by Pluralsight we will request
154         # only single format until formats listing was explicitly requested.
155         if self._downloader.params.get('listformats', False):
156             allowed_qualities = ALLOWED_QUALITIES
157         else:
158             def guess_allowed_qualities():
159                 req_format = self._downloader.params.get('format') or 'best'
160                 req_format_split = req_format.split('-')
161                 if len(req_format_split) > 1:
162                     req_ext, req_quality = req_format_split
163                     for allowed_quality in ALLOWED_QUALITIES:
164                         if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
165                             return (AllowedQuality(req_ext, (req_quality, )), )
166                 req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
167                 return (AllowedQuality(req_ext, ('high', )), )
168             allowed_qualities = guess_allowed_qualities()
169
170         formats = []
171         for ext, qualities in allowed_qualities:
172             for quality in qualities:
173                 f = QUALITIES[quality].copy()
174                 clip_post = {
175                     'a': author,
176                     'cap': 'false',
177                     'cn': clip_id,
178                     'course': course,
179                     'lc': 'en',
180                     'm': name,
181                     'mt': ext,
182                     'q': '%dx%d' % (f['width'], f['height']),
183                 }
184                 request = sanitized_Request(
185                     '%s/training/Player/ViewClip' % self._API_BASE,
186                     json.dumps(clip_post).encode('utf-8'))
187                 request.add_header('Content-Type', 'application/json;charset=utf-8')
188                 format_id = '%s-%s' % (ext, quality)
189                 clip_url = self._download_webpage(
190                     request, display_id, 'Downloading %s URL' % format_id, fatal=False)
191
192                 # Pluralsight tracks multiple sequential calls to ViewClip API and start
193                 # to return 429 HTTP errors after some time (see
194                 # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
195                 # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
196                 # To somewhat reduce the probability of these consequences
197                 # we will sleep random amount of time before each call to ViewClip.
198                 self._sleep(
199                     random.randint(2, 5), display_id,
200                     '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
201
202                 if not clip_url:
203                     continue
204                 f.update({
205                     'url': clip_url,
206                     'ext': ext,
207                     'format_id': format_id,
208                 })
209                 formats.append(f)
210         self._sort_formats(formats)
211
212         # TODO: captions
213         # http://www.pluralsight.com/training/Player/ViewClip + cap = true
214         # or
215         # http://www.pluralsight.com/training/Player/Captions
216         # { a = author, cn = clip_id, lc = end, m = name }
217
218         return {
219             'id': clip['clipName'],
220             'title': '%s - %s' % (module['title'], clip['title']),
221             'duration': int_or_none(clip.get('duration')) or parse_duration(clip.get('formattedDuration')),
222             'creator': author,
223             'formats': formats
224         }
225
226
227 class PluralsightCourseIE(PluralsightBaseIE):
228     IE_NAME = 'pluralsight:course'
229     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
230     _TESTS = [{
231         # Free course from Pluralsight Starter Subscription for Microsoft TechNet
232         # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
233         'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
234         'info_dict': {
235             'id': 'hosting-sql-server-windows-azure-iaas',
236             'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
237             'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
238         },
239         'playlist_count': 31,
240     }, {
241         # available without pluralsight account
242         'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
243         'only_matching': True,
244     }, {
245         'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
246         'only_matching': True,
247     }]
248
249     def _real_extract(self, url):
250         course_id = self._match_id(url)
251
252         # TODO: PSM cookie
253
254         course = self._download_json(
255             '%s/data/course/%s' % (self._API_BASE, course_id),
256             course_id, 'Downloading course JSON')
257
258         title = course['title']
259         description = course.get('description') or course.get('shortDescription')
260
261         course_data = self._download_json(
262             '%s/data/course/content/%s' % (self._API_BASE, course_id),
263             course_id, 'Downloading course data JSON')
264
265         entries = []
266         for module in course_data:
267             for clip in module.get('clips', []):
268                 player_parameters = clip.get('playerParameters')
269                 if not player_parameters:
270                     continue
271                 entries.append(self.url_result(
272                     '%s/training/player?%s' % (self._API_BASE, player_parameters),
273                     'Pluralsight'))
274
275         return self.playlist_result(entries, course_id, title, description)