1 from __future__ import unicode_literals
5 from .common import InfoExtractor
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'
25 def _real_initialize(self):
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
32 error = json_string.get(key)
34 raise ExtractorError('Unable to login: %s' % error, expected=True)
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')
41 if not action_url.startswith('http'):
42 action_url = compat_urlparse.urljoin(self._SIGNIN_URL, action_url)
44 form_data = self._hidden_inputs(form_html)
45 form_data.update(extra_form_data)
47 response = self._download_json(
48 action_url, None, note,
49 data=urlencode_postdata(form_data),
51 'Referer': referrer_url,
52 'X-Requested-With': 'XMLHttpRequest',
53 }, expected_status=(418, 500, ))
55 self._check_error(response, ('email', 'password', 'ErrorMessage'))
57 return response, action_url
60 username, password = self._get_login_info()
64 # Step 1: download signin page
65 signin_page = self._download_webpage(
66 self._SIGNIN_URL, None, 'Downloading signin page')
69 if any(re.search(p, signin_page) for p in (
70 r'isLoggedIn\s*:\s*true', r'logout\.aspx', r'>Log out<')):
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)
81 # Step 3: submit password
82 password_form = signin_page['body']
84 password_form, self._USER_URL, {'email': username, 'password': password},
85 'Submitting password', signin_url)
88 class LyndaIE(LyndaBaseIE):
90 IE_DESC = 'lynda.com videos'
93 (?:www\.)?(?:lynda\.com|educourse\.ga)/
95 (?:[^/]+/){2,3}(?P<course_id>\d+)|
101 _TIMECODE_REGEX = r'\[(?P<timecode>\d+:\d+:\d+[\.,]\d+)\]'
104 'url': 'https://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
109 'title': 'Using the exercise files',
113 'url': 'https://www.lynda.com/player/embed/133770?tr=foo=1;bar=g;fizz=rt&fs=0',
114 'only_matching': True,
116 'url': 'https://educourse.ga/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html',
117 'only_matching': True,
119 'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Willkommen-Grundlagen-guten-Gestaltung/393570/393572-4.html',
120 'only_matching': True,
123 def _raise_unavailable(self, video_id):
124 self.raise_login_required(
125 'Video %s is only available for members' % video_id)
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')
137 video = self._download_json(
138 'https://www.lynda.com/ajax/player', video_id,
139 'Downloading video JSON', fatal=False, query=query)
143 query['courseId'] = course_id
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')
150 self._raise_unavailable(video_id)
153 for formats_dict in play:
154 urls = formats_dict.get('urls')
155 if not isinstance(urls, dict):
157 cdn = formats_dict.get('name')
158 for format_id, format_url in urls.items():
163 'format_id': '%s-%s' % (cdn, format_id) if cdn else format_id,
164 'height': int_or_none(format_id),
166 self._sort_formats(formats)
168 conviva = self._download_json(
169 'https://www.lynda.com/ajax/player/conviva', video_id,
170 'Downloading conviva JSON', query=query)
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'),
182 if 'Status' in video:
183 raise ExtractorError(
184 'lynda returned error: %s' % video['Message'], expected=True)
186 if video.get('HasAccess') is False:
187 self._raise_unavailable(video_id)
189 video_id = compat_str(video.get('ID') or video_id)
190 duration = int_or_none(video.get('DurationInSeconds'))
191 title = video['Title']
195 fmts = video.get('Formats')
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')])
206 prioritized_streams = video.get('PrioritizedStreams')
207 if prioritized_streams:
208 for prioritized_stream_id, prioritized_stream in prioritized_streams.items():
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()])
215 self._check_formats(formats, video_id)
216 self._sort_formats(formats)
218 subtitles = self.extract_subtitles(video_id)
223 'duration': duration,
224 'subtitles': subtitles,
228 def _fix_subtitles(self, subs):
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:
236 seq_next = subs[pos + 1]
237 m_next = re.match(self._TIMECODE_REGEX, seq_next['Timecode'])
240 appear_time = m_current.group('timecode')
241 disappear_time = m_next.group('timecode')
242 text = seq_current['Caption'].strip()
245 srt += '%s\r\n%s --> %s\r\n%s\r\n\r\n' % (seq_counter, appear_time, disappear_time, text)
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)
254 return {'en': [{'ext': 'srt', 'data': fixed_subs}]}
259 class LyndaCourseIE(LyndaBaseIE):
260 IE_NAME = 'lynda:course'
261 IE_DESC = 'lynda.com online courses'
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'
268 'url': 'https://www.lynda.com/Graphic-Design-tutorials/Grundlagen-guten-Gestaltung/393570-2.html',
269 'only_matching': True,
271 'url': 'https://www.lynda.com/de/Graphic-Design-tutorials/Grundlagen-guten-Gestaltung/393570-2.html',
272 'only_matching': True,
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')
280 item_template = 'https://www.lynda.com/%s/%%s-4.html' % course_path
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)
287 webpage = self._download_webpage(url, course_id)
290 item_template % video_id, ie=LyndaIE.ie_key(),
292 for video_id in re.findall(
293 r'data-video-id=["\'](\d+)', webpage)]
294 return self.playlist_result(
296 self._og_search_title(webpage, fatal=False),
297 self._og_search_description(webpage))
299 if course.get('Status') == 'NotFound':
300 raise ExtractorError(
301 'Course %s does not exist' % course_id, expected=True)
303 unaccessible_videos = 0
306 # Might want to extract videos right here from video['Formats'] as it seems 'Formats' is not provided
307 # by single video API anymore
309 for chapter in course['Chapters']:
310 for video in chapter.get('Videos', []):
311 if video.get('HasAccess') is False:
312 unaccessible_videos += 1
314 video_id = video.get('ID')
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')),
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)
330 course_title = course.get('Title')
331 course_description = course.get('Description')
333 return self.playlist_result(entries, course_id, course_title, course_description)