[lynda] Add support for new authentication (Closes #9740)
[youtube-dl] / youtube_dl / extractor / lynda.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import (
7     compat_HTTPError,
8     compat_str,
9     compat_urlparse,
10 )
11 from ..utils import (
12     ExtractorError,
13     int_or_none,
14     urlencode_postdata,
15 )
16
17
18 class LyndaBaseIE(InfoExtractor):
19     _SIGNIN_URL = 'https://www.lynda.com/signin'
20     _PASSWORD_URL = 'https://www.lynda.com/signin/password'
21     _USER_URL = 'https://www.lynda.com/signin/user'
22     _ACCOUNT_CREDENTIALS_HINT = 'Use --username and --password options to provide lynda.com account credentials.'
23     _NETRC_MACHINE = 'lynda'
24
25     def _real_initialize(self):
26         self._login()
27
28     @staticmethod
29     def _check_error(json_string, key_or_keys):
30         keys = [key_or_keys] if isinstance(key_or_keys, compat_str) else key_or_keys
31         for key in keys:
32             error = json_string.get(key)
33             if error:
34                 raise ExtractorError('Unable to login: %s' % error, expected=True)
35
36     def _login_step(self, form_html, fallback_action_url, extra_form_data, note, referrer_url):
37         action_url = self._search_regex(
38             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', form_html,
39             'post url', default=fallback_action_url, group='url')
40
41         if not action_url.startswith('http'):
42             action_url = compat_urlparse.urljoin(self._SIGNIN_URL, action_url)
43
44         form_data = self._hidden_inputs(form_html)
45         form_data.update(extra_form_data)
46
47         try:
48             response = self._download_json(
49                 action_url, None, note,
50                 data=urlencode_postdata(form_data),
51                 headers={
52                     'Referer': referrer_url,
53                     'X-Requested-With': 'XMLHttpRequest',
54                 })
55         except ExtractorError as e:
56             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
57                 response = self._parse_json(e.cause.read().decode('utf-8'), None)
58                 self._check_error(response, ('email', 'password'))
59             raise
60
61         self._check_error(response, 'ErrorMessage')
62
63         return response, action_url
64
65     def _login(self):
66         username, password = self._get_login_info()
67         if username is None:
68             return
69
70         # Step 1: download signin page
71         signin_page = self._download_webpage(
72             self._SIGNIN_URL, None, 'Downloading signin page')
73
74         # Step 2: submit email
75         signin_form = self._search_regex(
76             r'(?s)(<form[^>]+data-form-name=["\']signin["\'][^>]*>.+?</form>)',
77             signin_page, 'signin form')
78         signin_page, signin_url = self._login_step(
79             signin_form, self._PASSWORD_URL, {'email': username},
80             'Submitting email', self._SIGNIN_URL)
81
82         # Step 3: submit password
83         password_form = signin_page['body']
84         self._login_step(
85             password_form, self._USER_URL, {'email': username, 'password': password},
86             'Submitting password', signin_url)
87
88     def _logout(self):
89         username, _ = self._get_login_info()
90         if username is None:
91             return
92
93         self._download_webpage(
94             'http://www.lynda.com/ajax/logout.aspx', None,
95             'Logging out', 'Unable to log out', fatal=False)
96
97
98 class LyndaIE(LyndaBaseIE):
99     IE_NAME = 'lynda'
100     IE_DESC = 'lynda.com videos'
101     _VALID_URL = r'https?://www\.lynda\.com/(?:[^/]+/[^/]+/\d+|player/embed)/(?P<id>\d+)'
102     _NETRC_MACHINE = 'lynda'
103
104     _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
105
106     _TESTS = [{
107         'url': 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
108         'md5': 'ecfc6862da89489161fb9cd5f5a6fac1',
109         'info_dict': {
110             'id': '114408',
111             'ext': 'mp4',
112             'title': 'Using the exercise files',
113             'duration': 68
114         }
115     }, {
116         'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
117         'only_matching': True,
118     }]
119
120     def _real_extract(self, url):
121         video_id = self._match_id(url)
122
123         video = self._download_json(
124             'http://www.lynda.com/ajax/player?videoId=%s&type=video' % video_id,
125             video_id, 'Downloading video JSON')
126
127         if 'Status' in video:
128             raise ExtractorError(
129                 'lynda returned error: %s' % video['Message'], expected=True)
130
131         if video.get('HasAccess') is False:
132             self.raise_login_required('Video %s is only available for members' % video_id)
133
134         video_id = compat_str(video.get('ID') or video_id)
135         duration = int_or_none(video.get('DurationInSeconds'))
136         title = video['Title']
137
138         formats = []
139
140         fmts = video.get('Formats')
141         if fmts:
142             formats.extend([{
143                 'url': f['Url'],
144                 'ext': f.get('Extension'),
145                 'width': int_or_none(f.get('Width')),
146                 'height': int_or_none(f.get('Height')),
147                 'filesize': int_or_none(f.get('FileSize')),
148                 'format_id': compat_str(f.get('Resolution')) if f.get('Resolution') else None,
149             } for f in fmts if f.get('Url')])
150
151         prioritized_streams = video.get('PrioritizedStreams')
152         if prioritized_streams:
153             for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
154                 formats.extend([{
155                     'url': video_url,
156                     'width': int_or_none(format_id),
157                     'format_id': '%s-%s' % (prioritized_stream_id, format_id),
158                 } for format_id, video_url in prioritized_stream.items()])
159
160         self._check_formats(formats, video_id)
161         self._sort_formats(formats)
162
163         subtitles = self.extract_subtitles(video_id)
164
165         return {
166             'id': video_id,
167             'title': title,
168             'duration': duration,
169             'subtitles': subtitles,
170             'formats': formats
171         }
172
173     def _fix_subtitles(self, subs):
174         srt = ''
175         seq_counter = 0
176         for pos in range(0, len(subs) - 1):
177             seq_current = subs[pos]
178             m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
179             if m_current is None:
180                 continue
181             seq_next = subs[pos + 1]
182             m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
183             if m_next is None:
184                 continue
185             appear_time = m_current.group('timecode')
186             disappear_time = m_next.group('timecode')
187             text = seq_current['Caption'].strip()
188             if text:
189                 seq_counter += 1
190                 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
191         if srt:
192             return srt
193
194     def _get_subtitles(self, video_id):
195         url = 'http://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
196         subs = self._download_json(url, None, False)
197         if subs:
198             return {'en': [{'ext': 'srt', 'data': self._fix_subtitles(subs)}]}
199         else:
200             return {}
201
202
203 class LyndaCourseIE(LyndaBaseIE):
204     IE_NAME = 'lynda:course'
205     IE_DESC = 'lynda.com online courses'
206
207     # Course link equals to welcome/introduction video link of same course
208     # We will recognize it as course link
209     _VALID_URL = r'https?://(?:www|m)\.lynda\.com/(?P<coursepath>[^/]+/[^/]+/(?P<courseid>\d+))-\d\.html'
210
211     def _real_extract(self, url):
212         mobj = re.match(self._VALID_URL, url)
213         course_path = mobj.group('coursepath')
214         course_id = mobj.group('courseid')
215
216         course = self._download_json(
217             'http://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
218             course_id, 'Downloading course JSON')
219
220         self._logout()
221
222         if course.get('Status') == 'NotFound':
223             raise ExtractorError(
224                 'Course %s does not exist' % course_id, expected=True)
225
226         unaccessible_videos = 0
227         entries = []
228
229         # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
230         # by single video API anymore
231
232         for chapter in course['Chapters']:
233             for video in chapter.get('Videos', []):
234                 if video.get('HasAccess') is False:
235                     unaccessible_videos += 1
236                     continue
237                 video_id = video.get('ID')
238                 if video_id:
239                     entries.append({
240                         '_type': 'url_transparent',
241                         'url': 'http://www.lynda.com/%s/%s-4.html' % (course_path, video_id),
242                         'ie_key': LyndaIE.ie_key(),
243                         'chapter': chapter.get('Title'),
244                         'chapter_number': int_or_none(chapter.get('ChapterIndex')),
245                         'chapter_id': compat_str(chapter.get('ID')),
246                     })
247
248         if unaccessible_videos > 0:
249             self._downloader.report_warning(
250                 '%s videos are only available for members (or paid members) and will not be downloaded. '
251                 % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT)
252
253         course_title = course.get('Title')
254
255         return self.playlist_result(entries, course_id, course_title)