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