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