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