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