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