[lynda] Simplify login and improve error capturing (#16891)
[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         response = self._download_json(
48             action_url, None, note,
49             data=urlencode_postdata(form_data),
50             headers={
51                 'Referer': referrer_url,
52                 'X-Requested-With': 'XMLHttpRequest',
53             }, expected_status=(418, 500, ))
54
55         self._check_error(response, ('email', 'password', 'ErrorMessage'))
56
57         return response, action_url
58
59     def _login(self):
60         username, password = self._get_login_info()
61         if username is None:
62             return
63
64         # Step 1: download signin page
65         signin_page = self._download_webpage(
66             self._SIGNIN_URL, None, 'Downloading signin page')
67
68         # Already logged in
69         if any(re.search(p, signin_page) for p in (
70                 r'isLoggedIn\s*:\s*true', r'logout\.aspx', r'>Log out<')):
71             return
72
73         # Step 2: submit email
74         signin_form = self._search_regex(
75             r'(?s)(<form[^>]+data-form-name=["\']signin["\'][^>]*>.+?</form>)',
76             signin_page, 'signin form')
77         signin_page, signin_url = self._login_step(
78             signin_form, self._PASSWORD_URL, {'email': username},
79             'Submitting email', self._SIGNIN_URL)
80
81         # Step 3: submit password
82         password_form = signin_page['body']
83         self._login_step(
84             password_form, self._USER_URL, {'email': username, 'password': password},
85             'Submitting password', signin_url)
86
87
88 class LyndaIE(LyndaBaseIE):
89     IE_NAME = 'lynda'
90     IE_DESC = 'lynda.com videos'
91     _VALID_URL = r'''(?x)
92                     https?://
93                         (?:www\.)?(?:lynda\.com|educourse\.ga)/
94                         (?:
95                             (?:[^/]+/){2,3}(?P<course_id>\d+)|
96                             player/embed
97                         )/
98                         (?P<id>\d+)
99                     '''
100
101     _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
102
103     _TESTS = [{
104         'url': 'https://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
105         # md5 is unstable
106         'info_dict': {
107             'id': '114408',
108             'ext': 'mp4',
109             'title': 'Using the exercise files',
110             'duration': 68
111         }
112     }, {
113         'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
114         'only_matching': True,
115     }, {
116         'url': 'https://educourse.ga/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
117         'only_matching': True,
118     }, {
119         'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Willkommen-Grundlagen-guten-Gestaltung/393570/393572-4.html',
120         'only_matching': True,
121     }]
122
123     def _raise_unavailable(self, video_id):
124         self.raise_login_required(
125             'Video %s is only available for members' % video_id)
126
127     def _real_extract(self, url):
128         mobj = re.match(self._VALID_URL, url)
129         video_id = mobj.group('id')
130         course_id = mobj.group('course_id')
131
132         query = {
133             'videoId': video_id,
134             'type': 'video',
135         }
136
137         video = self._download_json(
138             'https://www.lynda.com/ajax/player', video_id,
139             'Downloading video JSON', fatal=False, query=query)
140
141         # Fallback scenario
142         if not video:
143             query['courseId'] = course_id
144
145             play = self._download_json(
146                 'https://www.lynda.com/ajax/course/%s/%s/play'
147                 % (course_id, video_id), video_id, 'Downloading play JSON')
148
149             if not play:
150                 self._raise_unavailable(video_id)
151
152             formats = []
153             for formats_dict in play:
154                 urls = formats_dict.get('urls')
155                 if not isinstance(urls, dict):
156                     continue
157                 cdn = formats_dict.get('name')
158                 for format_id, format_url in urls.items():
159                     if not format_url:
160                         continue
161                     formats.append({
162                         'url': format_url,
163                         'format_id': '%s-%s' % (cdn, format_id) if cdn else format_id,
164                         'height': int_or_none(format_id),
165                     })
166             self._sort_formats(formats)
167
168             conviva = self._download_json(
169                 'https://www.lynda.com/ajax/player/conviva', video_id,
170                 'Downloading conviva JSON', query=query)
171
172             return {
173                 'id': video_id,
174                 'title': conviva['VideoTitle'],
175                 'description': conviva.get('VideoDescription'),
176                 'release_year': int_or_none(conviva.get('ReleaseYear')),
177                 'duration': int_or_none(conviva.get('Duration')),
178                 'creator': conviva.get('Author'),
179                 'formats': formats,
180             }
181
182         if 'Status' in video:
183             raise ExtractorError(
184                 'lynda returned error: %s' % video['Message'], expected=True)
185
186         if video.get('HasAccess') is False:
187             self._raise_unavailable(video_id)
188
189         video_id = compat_str(video.get('ID') or video_id)
190         duration = int_or_none(video.get('DurationInSeconds'))
191         title = video['Title']
192
193         formats = []
194
195         fmts = video.get('Formats')
196         if fmts:
197             formats.extend([{
198                 'url': f['Url'],
199                 'ext': f.get('Extension'),
200                 'width': int_or_none(f.get('Width')),
201                 'height': int_or_none(f.get('Height')),
202                 'filesize': int_or_none(f.get('FileSize')),
203                 'format_id': compat_str(f.get('Resolution')) if f.get('Resolution') else None,
204             } for f in fmts if f.get('Url')])
205
206         prioritized_streams = video.get('PrioritizedStreams')
207         if prioritized_streams:
208             for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
209                 formats.extend([{
210                     'url': video_url,
211                     'height': int_or_none(format_id),
212                     'format_id': '%s-%s' % (prioritized_stream_id, format_id),
213                 } for format_id, video_url in prioritized_stream.items()])
214
215         self._check_formats(formats, video_id)
216         self._sort_formats(formats)
217
218         subtitles = self.extract_subtitles(video_id)
219
220         return {
221             'id': video_id,
222             'title': title,
223             'duration': duration,
224             'subtitles': subtitles,
225             'formats': formats
226         }
227
228     def _fix_subtitles(self, subs):
229         srt = ''
230         seq_counter = 0
231         for pos in range(0, len(subs) - 1):
232             seq_current = subs[pos]
233             m_current = re.match(self._TIMECODE_REGEX, seq_current['Timecode'])
234             if m_current is None:
235                 continue
236             seq_next = subs[pos + 1]
237             m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
238             if m_next is None:
239                 continue
240             appear_time = m_current.group('timecode')
241             disappear_time = m_next.group('timecode')
242             text = seq_current['Caption'].strip()
243             if text:
244                 seq_counter += 1
245                 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
246         if srt:
247             return srt
248
249     def _get_subtitles(self, video_id):
250         url = 'https://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
251         subs = self._download_json(url, None, False)
252         fixed_subs = self._fix_subtitles(subs)
253         if fixed_subs:
254             return {'en': [{'ext': 'srt', 'data': fixed_subs}]}
255         else:
256             return {}
257
258
259 class LyndaCourseIE(LyndaBaseIE):
260     IE_NAME = 'lynda:course'
261     IE_DESC = 'lynda.com online courses'
262
263     # Course link equals to welcome/introduction video link of same course
264     # We will recognize it as course link
265     _VALID_URL = r'https?://(?:www|m)\.(?:lynda\.com|educourse\.ga)/(?P<coursepath>(?:[^/]+/){2,3}(?P<courseid>\d+))-2\.html'
266
267     _TESTS = [{
268         'url': 'https://www.lynda.com/Graphic-Design-tutorials/Grundlagen-guten-Gestaltung/393570-2.html',
269         'only_matching': True,
270     }, {
271         'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Grundlagen-guten-Gestaltung/393570-2.html',
272         'only_matching': True,
273     }]
274
275     def _real_extract(self, url):
276         mobj = re.match(self._VALID_URL, url)
277         course_path = mobj.group('coursepath')
278         course_id = mobj.group('courseid')
279
280         item_template = 'https://www.lynda.com/%s/%%s-4.html' % course_path
281
282         course = self._download_json(
283             'https://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
284             course_id, 'Downloading course JSON', fatal=False)
285
286         if not course:
287             webpage = self._download_webpage(url, course_id)
288             entries = [
289                 self.url_result(
290                     item_template % video_id, ie=LyndaIE.ie_key(),
291                     video_id=video_id)
292                 for video_id in re.findall(
293                     r'data-video-id=["\'](\d+)', webpage)]
294             return self.playlist_result(
295                 entries, course_id,
296                 self._og_search_title(webpage, fatal=False),
297                 self._og_search_description(webpage))
298
299         if course.get('Status') == 'NotFound':
300             raise ExtractorError(
301                 'Course %s does not exist' % course_id, expected=True)
302
303         unaccessible_videos = 0
304         entries = []
305
306         # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
307         # by single video API anymore
308
309         for chapter in course['Chapters']:
310             for video in chapter.get('Videos', []):
311                 if video.get('HasAccess') is False:
312                     unaccessible_videos += 1
313                     continue
314                 video_id = video.get('ID')
315                 if video_id:
316                     entries.append({
317                         '_type': 'url_transparent',
318                         'url': item_template % video_id,
319                         'ie_key': LyndaIE.ie_key(),
320                         'chapter': chapter.get('Title'),
321                         'chapter_number': int_or_none(chapter.get('ChapterIndex')),
322                         'chapter_id': compat_str(chapter.get('ID')),
323                     })
324
325         if unaccessible_videos > 0:
326             self._downloader.report_warning(
327                 '%s videos are only available for members (or paid members) and will not be downloaded. '
328                 % unaccessible_videos + self._ACCOUNT_CREDENTIALS_HINT)
329
330         course_title = course.get('Title')
331         course_description = course.get('Description')
332
333         return self.playlist_result(entries, course_id, course_title, course_description)