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