]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/udemy.py
[extractor] Add `_perform_login` function (#2943)
[yt-dlp.git] / yt_dlp / extractor / udemy.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_kwargs,
9 compat_str,
10 compat_urllib_request,
11 compat_urlparse,
12 )
13 from ..utils import (
14 determine_ext,
15 extract_attributes,
16 ExtractorError,
17 float_or_none,
18 int_or_none,
19 js_to_json,
20 sanitized_Request,
21 try_get,
22 unescapeHTML,
23 url_or_none,
24 urlencode_postdata,
25 )
26
27
28 class UdemyIE(InfoExtractor):
29 IE_NAME = 'udemy'
30 _VALID_URL = r'''(?x)
31 https?://
32 (?:[^/]+\.)?udemy\.com/
33 (?:
34 [^#]+\#/lecture/|
35 lecture/view/?\?lectureId=|
36 [^/]+/learn/v4/t/lecture/
37 )
38 (?P<id>\d+)
39 '''
40 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
41 _ORIGIN_URL = 'https://www.udemy.com'
42 _NETRC_MACHINE = 'udemy'
43
44 _TESTS = [{
45 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
46 'md5': '98eda5b657e752cf945d8445e261b5c5',
47 'info_dict': {
48 'id': '160614',
49 'ext': 'mp4',
50 'title': 'Introduction and Installation',
51 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
52 'duration': 579.29,
53 },
54 'skip': 'Requires udemy account credentials',
55 }, {
56 # new URL schema
57 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
58 'only_matching': True,
59 }, {
60 # no url in outputs format entry
61 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812',
62 'only_matching': True,
63 }, {
64 # only outputs rendition
65 'url': 'https://www.udemy.com/how-you-can-help-your-local-community-5-amazing-examples/learn/v4/t/lecture/3225750?start=0',
66 'only_matching': True,
67 }, {
68 'url': 'https://wipro.udemy.com/java-tutorial/#/lecture/172757',
69 'only_matching': True,
70 }]
71
72 def _extract_course_info(self, webpage, video_id):
73 course = self._parse_json(
74 unescapeHTML(self._search_regex(
75 r'ng-init=["\'].*\bcourse=({.+?})[;"\']',
76 webpage, 'course', default='{}')),
77 video_id, fatal=False) or {}
78 course_id = course.get('id') or self._search_regex(
79 [
80 r'data-course-id=["\'](\d+)',
81 r'&quot;courseId&quot;\s*:\s*(\d+)'
82 ], webpage, 'course id')
83 return course_id, course.get('title')
84
85 def _enroll_course(self, base_url, webpage, course_id):
86 def combine_url(base_url, url):
87 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
88
89 checkout_url = unescapeHTML(self._search_regex(
90 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
91 webpage, 'checkout url', group='url', default=None))
92 if checkout_url:
93 raise ExtractorError(
94 'Course %s is not free. You have to pay for it before you can download. '
95 'Use this URL to confirm purchase: %s'
96 % (course_id, combine_url(base_url, checkout_url)),
97 expected=True)
98
99 enroll_url = unescapeHTML(self._search_regex(
100 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
101 webpage, 'enroll url', group='url', default=None))
102 if enroll_url:
103 webpage = self._download_webpage(
104 combine_url(base_url, enroll_url),
105 course_id, 'Enrolling in the course',
106 headers={'Referer': base_url})
107 if '>You have enrolled in' in webpage:
108 self.to_screen('%s: Successfully enrolled in the course' % course_id)
109
110 def _download_lecture(self, course_id, lecture_id):
111 return self._download_json(
112 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?'
113 % (course_id, lecture_id),
114 lecture_id, 'Downloading lecture JSON', query={
115 'fields[lecture]': 'title,description,view_html,asset',
116 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,stream_urls,captions,data',
117 })
118
119 def _handle_error(self, response):
120 if not isinstance(response, dict):
121 return
122 error = response.get('error')
123 if error:
124 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
125 error_data = error.get('data')
126 if error_data:
127 error_str += ' - %s' % error_data.get('formErrors')
128 raise ExtractorError(error_str, expected=True)
129
130 def _download_webpage_handle(self, *args, **kwargs):
131 headers = kwargs.get('headers', {}).copy()
132 headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
133 kwargs['headers'] = headers
134 ret = super(UdemyIE, self)._download_webpage_handle(
135 *args, **compat_kwargs(kwargs))
136 if not ret:
137 return ret
138 webpage, _ = ret
139 if any(p in webpage for p in (
140 '>Please verify you are a human',
141 'Access to this page has been denied because we believe you are using automation tools to browse the website',
142 '"_pxCaptcha"')):
143 raise ExtractorError(
144 'Udemy asks you to solve a CAPTCHA. Login with browser, '
145 'solve CAPTCHA, then export cookies and pass cookie file to '
146 'yt-dlp with --cookies.', expected=True)
147 return ret
148
149 def _download_json(self, url_or_request, *args, **kwargs):
150 headers = {
151 'X-Udemy-Snail-Case': 'true',
152 'X-Requested-With': 'XMLHttpRequest',
153 }
154 for cookie in self._downloader.cookiejar:
155 if cookie.name == 'client_id':
156 headers['X-Udemy-Client-Id'] = cookie.value
157 elif cookie.name == 'access_token':
158 headers['X-Udemy-Bearer-Token'] = cookie.value
159 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
160
161 if isinstance(url_or_request, compat_urllib_request.Request):
162 for header, value in headers.items():
163 url_or_request.add_header(header, value)
164 else:
165 url_or_request = sanitized_Request(url_or_request, headers=headers)
166
167 response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
168 self._handle_error(response)
169 return response
170
171 def _perform_login(self, username, password):
172 login_popup = self._download_webpage(
173 self._LOGIN_URL, None, 'Downloading login popup')
174
175 def is_logged(webpage):
176 return any(re.search(p, webpage) for p in (
177 r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
178 r'>Logout<'))
179
180 # already logged in
181 if is_logged(login_popup):
182 return
183
184 login_form = self._form_hidden_inputs('login-form', login_popup)
185
186 login_form.update({
187 'email': username,
188 'password': password,
189 })
190
191 response = self._download_webpage(
192 self._LOGIN_URL, None, 'Logging in',
193 data=urlencode_postdata(login_form),
194 headers={
195 'Referer': self._ORIGIN_URL,
196 'Origin': self._ORIGIN_URL,
197 })
198
199 if not is_logged(response):
200 error = self._html_search_regex(
201 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
202 response, 'error message', default=None)
203 if error:
204 raise ExtractorError('Unable to login: %s' % error, expected=True)
205 raise ExtractorError('Unable to log in')
206
207 def _real_extract(self, url):
208 lecture_id = self._match_id(url)
209
210 webpage = self._download_webpage(url, lecture_id)
211
212 course_id, _ = self._extract_course_info(webpage, lecture_id)
213
214 try:
215 lecture = self._download_lecture(course_id, lecture_id)
216 except ExtractorError as e:
217 # Error could possibly mean we are not enrolled in the course
218 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
219 self._enroll_course(url, webpage, course_id)
220 lecture = self._download_lecture(course_id, lecture_id)
221 else:
222 raise
223
224 title = lecture['title']
225 description = lecture.get('description')
226
227 asset = lecture['asset']
228
229 asset_type = asset.get('asset_type') or asset.get('assetType')
230 if asset_type != 'Video':
231 raise ExtractorError(
232 'Lecture %s is not a video' % lecture_id, expected=True)
233
234 stream_url = asset.get('stream_url') or asset.get('streamUrl')
235 if stream_url:
236 youtube_url = self._search_regex(
237 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
238 if youtube_url:
239 return self.url_result(youtube_url, 'Youtube')
240
241 video_id = compat_str(asset['id'])
242 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
243 duration = float_or_none(asset.get('data', {}).get('duration'))
244
245 subtitles = {}
246 automatic_captions = {}
247
248 formats = []
249
250 def extract_output_format(src, f_id):
251 return {
252 'url': src.get('url'),
253 'format_id': '%sp' % (src.get('height') or f_id),
254 'width': int_or_none(src.get('width')),
255 'height': int_or_none(src.get('height')),
256 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
257 'vcodec': src.get('video_codec'),
258 'fps': int_or_none(src.get('frame_rate')),
259 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
260 'acodec': src.get('audio_codec'),
261 'asr': int_or_none(src.get('audio_sample_rate')),
262 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
263 'filesize': int_or_none(src.get('file_size_in_bytes')),
264 }
265
266 outputs = asset.get('data', {}).get('outputs')
267 if not isinstance(outputs, dict):
268 outputs = {}
269
270 def add_output_format_meta(f, key):
271 output = outputs.get(key)
272 if isinstance(output, dict):
273 output_format = extract_output_format(output, key)
274 output_format.update(f)
275 return output_format
276 return f
277
278 def extract_formats(source_list):
279 if not isinstance(source_list, list):
280 return
281 for source in source_list:
282 video_url = url_or_none(source.get('file') or source.get('src'))
283 if not video_url:
284 continue
285 if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
286 formats.extend(self._extract_m3u8_formats(
287 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
288 m3u8_id='hls', fatal=False))
289 continue
290 format_id = source.get('label')
291 f = {
292 'url': video_url,
293 'format_id': '%sp' % format_id,
294 'height': int_or_none(format_id),
295 }
296 if format_id:
297 # Some videos contain additional metadata (e.g.
298 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
299 f = add_output_format_meta(f, format_id)
300 formats.append(f)
301
302 def extract_subtitles(track_list):
303 if not isinstance(track_list, list):
304 return
305 for track in track_list:
306 if not isinstance(track, dict):
307 continue
308 if track.get('kind') != 'captions':
309 continue
310 src = url_or_none(track.get('src'))
311 if not src:
312 continue
313 lang = track.get('language') or track.get(
314 'srclang') or track.get('label')
315 sub_dict = automatic_captions if track.get(
316 'autogenerated') is True else subtitles
317 sub_dict.setdefault(lang, []).append({
318 'url': src,
319 })
320
321 for url_kind in ('download', 'stream'):
322 urls = asset.get('%s_urls' % url_kind)
323 if isinstance(urls, dict):
324 extract_formats(urls.get('Video'))
325
326 captions = asset.get('captions')
327 if isinstance(captions, list):
328 for cc in captions:
329 if not isinstance(cc, dict):
330 continue
331 cc_url = url_or_none(cc.get('url'))
332 if not cc_url:
333 continue
334 lang = try_get(cc, lambda x: x['locale']['locale'], compat_str)
335 sub_dict = (automatic_captions if cc.get('source') == 'auto'
336 else subtitles)
337 sub_dict.setdefault(lang or 'en', []).append({
338 'url': cc_url,
339 })
340
341 view_html = lecture.get('view_html')
342 if view_html:
343 view_html_urls = set()
344 for source in re.findall(r'<source[^>]+>', view_html):
345 attributes = extract_attributes(source)
346 src = attributes.get('src')
347 if not src:
348 continue
349 res = attributes.get('data-res')
350 height = int_or_none(res)
351 if src in view_html_urls:
352 continue
353 view_html_urls.add(src)
354 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
355 m3u8_formats = self._extract_m3u8_formats(
356 src, video_id, 'mp4', entry_protocol='m3u8_native',
357 m3u8_id='hls', fatal=False)
358 for f in m3u8_formats:
359 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
360 if m:
361 if not f.get('height'):
362 f['height'] = int(m.group('height'))
363 if not f.get('tbr'):
364 f['tbr'] = int(m.group('tbr'))
365 formats.extend(m3u8_formats)
366 else:
367 formats.append(add_output_format_meta({
368 'url': src,
369 'format_id': '%dp' % height if height else None,
370 'height': height,
371 }, res))
372
373 # react rendition since 2017.04.15 (see
374 # https://github.com/ytdl-org/youtube-dl/issues/12744)
375 data = self._parse_json(
376 self._search_regex(
377 r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
378 'setup data', default='{}', group='data'), video_id,
379 transform_source=unescapeHTML, fatal=False)
380 if data and isinstance(data, dict):
381 extract_formats(data.get('sources'))
382 if not duration:
383 duration = int_or_none(data.get('duration'))
384 extract_subtitles(data.get('tracks'))
385
386 if not subtitles and not automatic_captions:
387 text_tracks = self._parse_json(
388 self._search_regex(
389 r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html,
390 'text tracks', default='{}', group='data'), video_id,
391 transform_source=lambda s: js_to_json(unescapeHTML(s)),
392 fatal=False)
393 extract_subtitles(text_tracks)
394
395 if not formats and outputs:
396 for format_id, output in outputs.items():
397 f = extract_output_format(output, format_id)
398 if f.get('url'):
399 formats.append(f)
400
401 self._sort_formats(formats)
402
403 return {
404 'id': video_id,
405 'title': title,
406 'description': description,
407 'thumbnail': thumbnail,
408 'duration': duration,
409 'formats': formats,
410 'subtitles': subtitles,
411 'automatic_captions': automatic_captions,
412 }
413
414
415 class UdemyCourseIE(UdemyIE):
416 IE_NAME = 'udemy:course'
417 _VALID_URL = r'https?://(?:[^/]+\.)?udemy\.com/(?P<id>[^/?#&]+)'
418 _TESTS = [{
419 'url': 'https://www.udemy.com/java-tutorial/',
420 'only_matching': True,
421 }, {
422 'url': 'https://wipro.udemy.com/java-tutorial/',
423 'only_matching': True,
424 }]
425
426 @classmethod
427 def suitable(cls, url):
428 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
429
430 def _real_extract(self, url):
431 course_path = self._match_id(url)
432
433 webpage = self._download_webpage(url, course_path)
434
435 course_id, title = self._extract_course_info(webpage, course_path)
436
437 self._enroll_course(url, webpage, course_id)
438
439 response = self._download_json(
440 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
441 course_id, 'Downloading course curriculum', query={
442 'fields[chapter]': 'title,object_index',
443 'fields[lecture]': 'title,asset',
444 'page_size': '1000',
445 })
446
447 entries = []
448 chapter, chapter_number = [None] * 2
449 for entry in response['results']:
450 clazz = entry.get('_class')
451 if clazz == 'lecture':
452 asset = entry.get('asset')
453 if isinstance(asset, dict):
454 asset_type = asset.get('asset_type') or asset.get('assetType')
455 if asset_type != 'Video':
456 continue
457 lecture_id = entry.get('id')
458 if lecture_id:
459 entry = {
460 '_type': 'url_transparent',
461 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
462 'title': entry.get('title'),
463 'ie_key': UdemyIE.ie_key(),
464 }
465 if chapter_number:
466 entry['chapter_number'] = chapter_number
467 if chapter:
468 entry['chapter'] = chapter
469 entries.append(entry)
470 elif clazz == 'chapter':
471 chapter_number = entry.get('object_index')
472 chapter = entry.get('title')
473
474 return self.playlist_result(entries, course_id, title)