[pluralsight] Extract base class
[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     def _real_extract(self, url):
88         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
89
90         author = qs.get('author', [None])[0]
91         name = qs.get('name', [None])[0]
92         clip_id = qs.get('clip', [None])[0]
93         course = qs.get('course', [None])[0]
94
95         if any(not f for f in (author, name, clip_id, course,)):
96             raise ExtractorError('Invalid URL', expected=True)
97
98         display_id = '%s-%s' % (name, clip_id)
99
100         webpage = self._download_webpage(url, display_id)
101
102         collection = self._parse_json(
103             self._search_regex(
104                 r'moduleCollection\s*:\s*new\s+ModuleCollection\((\[.+?\])\s*,\s*\$rootScope\)',
105                 webpage, 'modules'),
106             display_id)
107
108         module, clip = None, None
109
110         for module_ in collection:
111             if module_.get('moduleName') == name:
112                 module = module_
113                 for clip_ in module_.get('clips', []):
114                     clip_index = clip_.get('clipIndex')
115                     if clip_index is None:
116                         continue
117                     if compat_str(clip_index) == clip_id:
118                         clip = clip_
119                         break
120
121         if not clip:
122             raise ExtractorError('Unable to resolve clip')
123
124         QUALITIES = {
125             'low': {'width': 640, 'height': 480},
126             'medium': {'width': 848, 'height': 640},
127             'high': {'width': 1024, 'height': 768},
128         }
129
130         ALLOWED_QUALITIES = (
131             ('webm', ('high',)),
132             ('mp4', ('low', 'medium', 'high',)),
133         )
134
135         formats = []
136         for ext, qualities in ALLOWED_QUALITIES:
137             for quality in qualities:
138                 f = QUALITIES[quality].copy()
139                 clip_post = {
140                     'a': author,
141                     'cap': 'false',
142                     'cn': clip_id,
143                     'course': course,
144                     'lc': 'en',
145                     'm': name,
146                     'mt': ext,
147                     'q': '%dx%d' % (f['width'], f['height']),
148                 }
149                 request = compat_urllib_request.Request(
150                     '%s/training/Player/ViewClip' % self._API_BASE,
151                     json.dumps(clip_post).encode('utf-8'))
152                 request.add_header('Content-Type', 'application/json;charset=utf-8')
153                 format_id = '%s-%s' % (ext, quality)
154                 clip_url = self._download_webpage(
155                     request, display_id, 'Downloading %s URL' % format_id, fatal=False)
156                 if not clip_url:
157                     continue
158                 f.update({
159                     'url': clip_url,
160                     'ext': ext,
161                     'format_id': format_id,
162                 })
163                 formats.append(f)
164         self._sort_formats(formats)
165
166         # TODO: captions
167         # http://www.pluralsight.com/training/Player/ViewClip + cap = true
168         # or
169         # http://www.pluralsight.com/training/Player/Captions
170         # { a = author, cn = clip_id, lc = end, m = name }
171
172         return {
173             'id': clip['clipName'],
174             'title': '%s - %s' % (module['title'], clip['title']),
175             'duration': int_or_none(clip.get('duration')) or parse_duration(clip.get('formattedDuration')),
176             'creator': author,
177             'formats': formats
178         }
179
180
181 class PluralsightCourseIE(PluralsightBaseIE):
182     IE_NAME = 'pluralsight:course'
183     _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
184     _TESTS = [{
185         # Free course from Pluralsight Starter Subscription for Microsoft TechNet
186         # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
187         'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
188         'info_dict': {
189             'id': 'hosting-sql-server-windows-azure-iaas',
190             'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
191             'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
192         },
193         'playlist_count': 31,
194     }, {
195         # available without pluralsight account
196         'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
197         'only_matching': True,
198     }, {
199         'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
200         'only_matching': True,
201     }]
202
203     def _real_extract(self, url):
204         course_id = self._match_id(url)
205
206         # TODO: PSM cookie
207
208         course = self._download_json(
209             '%s/data/course/%s' % (self._API_BASE, course_id),
210             course_id, 'Downloading course JSON')
211
212         title = course['title']
213         description = course.get('description') or course.get('shortDescription')
214
215         course_data = self._download_json(
216             '%s/data/course/content/%s' % (self._API_BASE, course_id),
217             course_id, 'Downloading course data JSON')
218
219         entries = []
220         for module in course_data:
221             for clip in module.get('clips', []):
222                 player_parameters = clip.get('playerParameters')
223                 if not player_parameters:
224                     continue
225                 entries.append(self.url_result(
226                     '%s/training/player?%s' % (self._API_BASE, player_parameters),
227                     'Pluralsight'))
228
229         return self.playlist_result(entries, course_id, title, description)