[pluralsight] prevent error 429 when sensing video formats
[youtube-dl] / youtube_dl / extractor / pluralsight.py
1 from __future__ import unicode_literals
2
3 import json
4
5 from .common import InfoExtractor
6 from ..compat import (
7     compat_str,
8     compat_urllib_parse,
9     compat_urllib_request,
10     compat_urlparse,
11 )
12 from ..utils import (
13     ExtractorError,
14     int_or_none,
15     parse_duration,
16 )
17
18
19 class PluralsightBaseIE(InfoExtractor):
20     _API_BASE = 'http://app.pluralsight.com'
21
22
23 class PluralsightIE(PluralsightBaseIE):
24     IE_NAME = 'pluralsight'
25     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/training/player\?'
26     _LOGIN_URL = 'https://app.pluralsight.com/id/'
27
28     _NETRC_MACHINE = 'pluralsight'
29
30     _TESTS = [{
31         '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',
32         'md5': '4d458cf5cf4c593788672419a8dd4cf8',
33         'info_dict': {
34             'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
35             'ext': 'mp4',
36             'title': 'Management of SQL Server - Demo Monitoring',
37             'duration': 338,
38         },
39         'skip': 'Requires pluralsight account credentials',
40     }, {
41         'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
42         'only_matching': True,
43     }, {
44         # available without pluralsight account
45         'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
46         'only_matching': True,
47     }]
48
49     def _real_initialize(self):
50         self._login()
51
52     def _login(self):
53         (username, password) = self._get_login_info()
54         if username is None:
55             return
56
57         login_page = self._download_webpage(
58             self._LOGIN_URL, None, 'Downloading login page')
59
60         login_form = self._hidden_inputs(login_page)
61
62         login_form.update({
63             'Username': username.encode('utf-8'),
64             'Password': password.encode('utf-8'),
65         })
66
67         post_url = self._search_regex(
68             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
69             'post url', default=self._LOGIN_URL, group='url')
70
71         if not post_url.startswith('http'):
72             post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
73
74         request = compat_urllib_request.Request(
75             post_url, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
76         request.add_header('Content-Type', 'application/x-www-form-urlencoded')
77
78         response = self._download_webpage(
79             request, None, 'Logging in as %s' % username)
80
81         error = self._search_regex(
82             r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
83             response, 'error message', default=None)
84         if error:
85             raise ExtractorError('Unable to login: %s' % error, expected=True)
86
87         if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
88             raise ExtractorError('Unable to log in')
89
90     def _real_extract(self, url):
91         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
92
93         author = qs.get('author', [None])[0]
94         name = qs.get('name', [None])[0]
95         clip_id = qs.get('clip', [None])[0]
96         course = qs.get('course', [None])[0]
97
98         if any(not f for f in (author, name, clip_id, course,)):
99             raise ExtractorError('Invalid URL', expected=True)
100
101         display_id = '%s-%s' % (name, clip_id)
102
103         webpage = self._download_webpage(url, display_id)
104
105         collection = self._parse_json(
106             self._search_regex(
107                 r'moduleCollection\s*:\s*new\s+ModuleCollection\((\[.+?\])\s*,\s*\$rootScope\)',
108                 webpage, 'modules'),
109             display_id)
110
111         module, clip = None, None
112
113         for module_ in collection:
114             if module_.get('moduleName') == name:
115                 module = module_
116                 for clip_ in module_.get('clips', []):
117                     clip_index = clip_.get('clipIndex')
118                     if clip_index is None:
119                         continue
120                     if compat_str(clip_index) == clip_id:
121                         clip = clip_
122                         break
123
124         if not clip:
125             raise ExtractorError('Unable to resolve clip')
126
127         QUALITIES = {
128             'low': {'width': 640, 'height': 480},
129             'medium': {'width': 848, 'height': 640},
130             'high': {'width': 1024, 'height': 768},
131         }
132
133         ALLOWED_QUALITIES = (
134             ('webm', ('high',)),
135             ('mp4', ('low', 'medium', 'high',)),
136         )
137
138         formats = []
139         for ext, qualities in ALLOWED_QUALITIES:
140             for quality in qualities:
141                 f = QUALITIES[quality].copy()
142                 clip_post = {
143                     'a': author,
144                     'cap': 'false',
145                     'cn': clip_id,
146                     'course': course,
147                     'lc': 'en',
148                     'm': name,
149                     'mt': ext,
150                     'q': '%dx%d' % (f['width'], f['height']),
151                 }
152                 request = compat_urllib_request.Request(
153                     '%s/training/Player/ViewClip' % self._API_BASE,
154                     json.dumps(clip_post).encode('utf-8'))
155                 request.add_header('Content-Type', 'application/json;charset=utf-8')
156                 format_id = '%s-%s' % (ext, quality)
157                 clip_url = self._download_webpage(
158                     request, display_id, 'Downloading %s URL' % format_id, fatal=False)
159                 # #6989: sleep 3 seconds to avoid 429 errors.
160                 # should help with #6842.
161                 self._sleep(3, display_id)
162                 if not clip_url:
163                     continue
164                 f.update({
165                     'url': clip_url,
166                     'ext': ext,
167                     'format_id': format_id,
168                 })
169                 formats.append(f)
170         self._sort_formats(formats)
171
172         # TODO: captions
173         # http://www.pluralsight.com/training/Player/ViewClip + cap = true
174         # or
175         # http://www.pluralsight.com/training/Player/Captions
176         # { a = author, cn = clip_id, lc = end, m = name }
177
178         return {
179             'id': clip['clipName'],
180             'title': '%s - %s' % (module['title'], clip['title']),
181             'duration': int_or_none(clip.get('duration')) or parse_duration(clip.get('formattedDuration')),
182             'creator': author,
183             'formats': formats
184         }
185
186
187 class PluralsightCourseIE(PluralsightBaseIE):
188     IE_NAME = 'pluralsight:course'
189     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
190     _TESTS = [{
191         # Free course from Pluralsight Starter Subscription for Microsoft TechNet
192         # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
193         'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
194         'info_dict': {
195             'id': 'hosting-sql-server-windows-azure-iaas',
196             'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
197             'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
198         },
199         'playlist_count': 31,
200     }, {
201         # available without pluralsight account
202         'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
203         'only_matching': True,
204     }, {
205         'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
206         'only_matching': True,
207     }]
208
209     def _real_extract(self, url):
210         course_id = self._match_id(url)
211
212         # TODO: PSM cookie
213
214         course = self._download_json(
215             '%s/data/course/%s' % (self._API_BASE, course_id),
216             course_id, 'Downloading course JSON')
217
218         title = course['title']
219         description = course.get('description') or course.get('shortDescription')
220
221         course_data = self._download_json(
222             '%s/data/course/content/%s' % (self._API_BASE, course_id),
223             course_id, 'Downloading course data JSON')
224
225         entries = []
226         for module in course_data:
227             for clip in module.get('clips', []):
228                 player_parameters = clip.get('playerParameters')
229                 if not player_parameters:
230                     continue
231                 entries.append(self.url_result(
232                     '%s/training/player?%s' % (self._API_BASE, player_parameters),
233                     'Pluralsight'))
234
235         return self.playlist_result(entries, course_id, title, description)