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