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