[pluralsight] Improve login detection
[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                 if not clip_url:
160                     continue
161                 f.update({
162                     'url': clip_url,
163                     'ext': ext,
164                     'format_id': format_id,
165                 })
166                 formats.append(f)
167         self._sort_formats(formats)
168
169         # TODO: captions
170         # http://www.pluralsight.com/training/Player/ViewClip + cap = true
171         # or
172         # http://www.pluralsight.com/training/Player/Captions
173         # { a = author, cn = clip_id, lc = end, m = name }
174
175         return {
176             'id': clip['clipName'],
177             'title': '%s - %s' % (module['title'], clip['title']),
178             'duration': int_or_none(clip.get('duration')) or parse_duration(clip.get('formattedDuration')),
179             'creator': author,
180             'formats': formats
181         }
182
183
184 class PluralsightCourseIE(PluralsightBaseIE):
185     IE_NAME = 'pluralsight:course'
186     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
187     _TESTS = [{
188         # Free course from Pluralsight Starter Subscription for Microsoft TechNet
189         # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
190         'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
191         'info_dict': {
192             'id': 'hosting-sql-server-windows-azure-iaas',
193             'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
194             'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
195         },
196         'playlist_count': 31,
197     }, {
198         # available without pluralsight account
199         'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
200         'only_matching': True,
201     }, {
202         'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
203         'only_matching': True,
204     }]
205
206     def _real_extract(self, url):
207         course_id = self._match_id(url)
208
209         # TODO: PSM cookie
210
211         course = self._download_json(
212             '%s/data/course/%s' % (self._API_BASE, course_id),
213             course_id, 'Downloading course JSON')
214
215         title = course['title']
216         description = course.get('description') or course.get('shortDescription')
217
218         course_data = self._download_json(
219             '%s/data/course/content/%s' % (self._API_BASE, course_id),
220             course_id, 'Downloading course data JSON')
221
222         entries = []
223         for module in course_data:
224             for clip in module.get('clips', []):
225                 player_parameters = clip.get('playerParameters')
226                 if not player_parameters:
227                     continue
228                 entries.append(self.url_result(
229                     '%s/training/player?%s' % (self._API_BASE, player_parameters),
230                     'Pluralsight'))
231
232         return self.playlist_result(entries, course_id, title, description)