]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/lynda.py
[lynda] Simplify login and improve error capturing (#16891)
[yt-dlp.git] / youtube_dl / extractor / lynda.py
CommitLineData
a7c26e73
PH
1from __future__ import unicode_literals
2
c7f8537d 3import re
c7f8537d 4
5from .common import InfoExtractor
bdf16f81
S
6from ..compat import (
7 compat_HTTPError,
8 compat_str,
9 compat_urlparse,
10)
1cc79574 11from ..utils import (
16ff7ebc
S
12 ExtractorError,
13 int_or_none,
6e6bc8da 14 urlencode_postdata,
7ee40b5d 15)
c7f8537d 16
17
30cbd4e0 18class LyndaBaseIE(InfoExtractor):
bdf16f81
S
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'
30cbd4e0 22 _ACCOUNT_CREDENTIALS_HINT = 'Use --username and --password options to provide lynda.com account credentials.'
499bfcbf 23 _NETRC_MACHINE = 'lynda'
30cbd4e0
S
24
25 def _real_initialize(self):
26 self._login()
27
bdf16f81
S
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
5621c322
S
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, ))
bdf16f81 54
5621c322 55 self._check_error(response, ('email', 'password', 'ErrorMessage'))
bdf16f81
S
56
57 return response, action_url
58
30cbd4e0 59 def _login(self):
0d85c3a7 60 username, password = self._get_login_info()
30cbd4e0
S
61 if username is None:
62 return
63
bdf16f81
S
64 # Step 1: download signin page
65 signin_page = self._download_webpage(
66 self._SIGNIN_URL, None, 'Downloading signin page')
67
3841256c
S
68 # Already logged in
69 if any(re.search(p, signin_page) for p in (
ec85ded8 70 r'isLoggedIn\s*:\s*true', r'logout\.aspx', r'>Log out<')):
3841256c
S
71 return
72
bdf16f81
S
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)
30cbd4e0
S
86
87
88class LyndaIE(LyndaBaseIE):
a7c26e73
PH
89 IE_NAME = 'lynda'
90 IE_DESC = 'lynda.com videos'
b7c74c04
S
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 '''
7ee40b5d 100
7ee40b5d 101 _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
102
a0d64613 103 _TESTS = [{
68d9561c 104 'url': 'https://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
61a98b86 105 # md5 is unstable
ac260dd8 106 'info_dict': {
136db788
S
107 'id': '114408',
108 'ext': 'mp4',
a7c26e73
PH
109 'title': 'Using the exercise files',
110 'duration': 68
c7f8537d 111 }
a0d64613
S
112 }, {
113 'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
114 'only_matching': True,
8c6919e4
S
115 }, {
116 'url': 'https://educourse.ga/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
117 'only_matching': True,
b7c74c04
S
118 }, {
119 'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Willkommen-Grundlagen-guten-Gestaltung/393570/393572-4.html',
120 'only_matching': True,
a0d64613 121 }]
7ee40b5d 122
6edfc40a
S
123 def _raise_unavailable(self, video_id):
124 self.raise_login_required(
125 'Video %s is only available for members' % video_id)
126
c7f8537d 127 def _real_extract(self, url):
6edfc40a
S
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 }
c7f8537d 136
ea8ed40b 137 video = self._download_json(
6edfc40a
S
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 }
c7f8537d 181
ea8ed40b 182 if 'Status' in video:
30cbd4e0 183 raise ExtractorError(
ea8ed40b 184 'lynda returned error: %s' % video['Message'], expected=True)
c7f8537d 185
ea8ed40b 186 if video.get('HasAccess') is False:
6edfc40a 187 self._raise_unavailable(video_id)
c7f8537d 188
ea8ed40b
S
189 video_id = compat_str(video.get('ID') or video_id)
190 duration = int_or_none(video.get('DurationInSeconds'))
191 title = video['Title']
c7f8537d 192
16ff7ebc
S
193 formats = []
194
ea8ed40b 195 fmts = video.get('Formats')
16ff7ebc 196 if fmts:
ea8ed40b
S
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')
16ff7ebc 207 if prioritized_streams:
5a11b793 208 for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
ea8ed40b
S
209 formats.extend([{
210 'url': video_url,
ea8aefd1 211 'height': int_or_none(format_id),
ea8ed40b
S
212 'format_id': '%s-%s' % (prioritized_stream_id, format_id),
213 } for format_id, video_url in prioritized_stream.items()])
c7f8537d 214
a57e8ce6 215 self._check_formats(formats, video_id)
c7f8537d 216 self._sort_formats(formats)
7ee40b5d 217
ea8ed40b 218 subtitles = self.extract_subtitles(video_id)
7ee40b5d 219
c7f8537d 220 return {
221 'id': video_id,
222 'title': title,
223 'duration': duration,
62bcfa8c 224 'subtitles': subtitles,
c7f8537d 225 'formats': formats
226 }
7ee40b5d 227
311c3938
JMF
228 def _fix_subtitles(self, subs):
229 srt = ''
7594be85 230 seq_counter = 0
311c3938
JMF
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:
62bcfa8c 239 continue
311c3938
JMF
240 appear_time = m_current.group('timecode')
241 disappear_time = m_next.group('timecode')
7594be85
S
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)
311c3938
JMF
246 if srt:
247 return srt
248
ea8ed40b 249 def _get_subtitles(self, video_id):
68d9561c 250 url = 'https://www.lynda.com/ajax/player?videoId=%s&type=transcript' % video_id
311c3938 251 subs = self._download_json(url, None, False)
75ba0efb
S
252 fixed_subs = self._fix_subtitles(subs)
253 if fixed_subs:
254 return {'en': [{'ext': 'srt', 'data': fixed_subs}]}
311c3938
JMF
255 else:
256 return {}
c7f8537d 257
258
30cbd4e0 259class LyndaCourseIE(LyndaBaseIE):
a7c26e73
PH
260 IE_NAME = 'lynda:course'
261 IE_DESC = 'lynda.com online courses'
c7f8537d 262
263 # Course link equals to welcome/introduction video link of same course
264 # We will recognize it as course link
b7c74c04
S
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 }]
c7f8537d 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')
5f6a1245 279
f2980fdd
S
280 item_template = 'https://www.lynda.com/%s/%%s-4.html' % course_path
281
71bb0161 282 course = self._download_json(
68d9561c 283 'https://www.lynda.com/ajax/player?courseId=%s&type=course' % course_id,
f2980fdd
S
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))
c7f8537d 298
71bb0161 299 if course.get('Status') == 'NotFound':
30cbd4e0
S
300 raise ExtractorError(
301 'Course %s does not exist' % course_id, expected=True)
c7f8537d 302
303 unaccessible_videos = 0
00322ad4 304 entries = []
c7f8537d 305
16ff7ebc
S
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
71bb0161
S
309 for chapter in course['Chapters']:
310 for video in chapter.get('Videos', []):
311 if video.get('HasAccess') is False:
c7f8537d 312 unaccessible_videos += 1
313 continue
00322ad4
S
314 video_id = video.get('ID')
315 if video_id:
316 entries.append({
317 '_type': 'url_transparent',
f2980fdd 318 'url': item_template % video_id,
00322ad4
S
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 })
c7f8537d 324
325 if unaccessible_videos > 0:
30cbd4e0
S
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)
c7f8537d 329
71bb0161 330 course_title = course.get('Title')
04343588 331 course_description = course.get('Description')
c7f8537d 332
04343588 333 return self.playlist_result(entries, course_id, course_title, course_description)