]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/udemy.py
[extractor/udemy] Fix lectures that have no URL and detect DRM
[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,
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
ac668111 156 if isinstance(url_or_request, urllib.request.Request):
61c0663c
S
157 for header, value in headers.items():
158 url_or_request.add_header(header, value)
159 else:
5c2266df 160 url_or_request = sanitized_Request(url_or_request, headers=headers)
61c0663c 161
81da8cbc 162 response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
61c0663c
S
163 self._handle_error(response)
164 return response
e2937118 165
52efa4b3 166 def _perform_login(self, username, password):
e5de3f6c 167 login_popup = self._download_webpage(
dcd4d95c 168 self._LOGIN_URL, None, 'Downloading login popup')
e5de3f6c 169
d609edf4 170 def is_logged(webpage):
807cf7b0
S
171 return any(re.search(p, webpage) for p in (
172 r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
173 r'>Logout<'))
d609edf4
S
174
175 # already logged in
176 if is_logged(login_popup):
e5de3f6c
S
177 return
178
dcd4d95c 179 login_form = self._form_hidden_inputs('login-form', login_popup)
e5de3f6c 180
dcd4d95c 181 login_form.update({
a3373823
S
182 'email': username,
183 'password': password,
dcd4d95c
S
184 })
185
dcd4d95c 186 response = self._download_webpage(
e4d95865 187 self._LOGIN_URL, None, 'Logging in',
75b81df3
S
188 data=urlencode_postdata(login_form),
189 headers={
190 'Referer': self._ORIGIN_URL,
191 'Origin': self._ORIGIN_URL,
192 })
e5de3f6c 193
d609edf4 194 if not is_logged(response):
dcd4d95c
S
195 error = self._html_search_regex(
196 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
197 response, 'error message', default=None)
198 if error:
199 raise ExtractorError('Unable to login: %s' % error, expected=True)
e5de3f6c
S
200 raise ExtractorError('Unable to log in')
201
202 def _real_extract(self, url):
810fb84d 203 lecture_id = self._match_id(url)
8d1ddb08 204 course_id = unsmuggle_url(url, {})[1].get('course_id')
e5de3f6c 205
8d1ddb08 206 webpage = None
207 if not course_id:
208 webpage = self._download_webpage(url, lecture_id)
209 course_id, _ = self._extract_course_info(webpage, lecture_id)
e5de3f6c 210
328f82d5
S
211 try:
212 lecture = self._download_lecture(course_id, lecture_id)
213 except ExtractorError as e:
214 # Error could possibly mean we are not enrolled in the course
215 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
8d1ddb08 216 webpage = webpage or self._download_webpage(url, lecture_id)
ff9d5d09 217 self._enroll_course(url, webpage, course_id)
3092fc40 218 lecture = self._download_lecture(course_id, lecture_id)
328f82d5
S
219 else:
220 raise
221
222 title = lecture['title']
223 description = lecture.get('description')
224
225 asset = lecture['asset']
226
03caa463 227 asset_type = asset.get('asset_type') or asset.get('assetType')
e2937118
S
228 if asset_type != 'Video':
229 raise ExtractorError(
230 'Lecture %s is not a video' % lecture_id, expected=True)
e5de3f6c 231
03caa463 232 stream_url = asset.get('stream_url') or asset.get('streamUrl')
328f82d5
S
233 if stream_url:
234 youtube_url = self._search_regex(
235 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
236 if youtube_url:
237 return self.url_result(youtube_url, 'Youtube')
e5de3f6c 238
0a439c5c 239 video_id = compat_str(asset['id'])
03caa463 240 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
328f82d5 241 duration = float_or_none(asset.get('data', {}).get('duration'))
328f82d5 242
3dfceb28
S
243 subtitles = {}
244 automatic_captions = {}
245
328f82d5 246 formats = []
f0e83681 247
3dfceb28 248 def extract_output_format(src, f_id):
f0e83681 249 return {
b7f87493 250 'url': src.get('url'),
3dfceb28 251 'format_id': '%sp' % (src.get('height') or f_id),
f0e83681
S
252 'width': int_or_none(src.get('width')),
253 'height': int_or_none(src.get('height')),
254 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
255 'vcodec': src.get('video_codec'),
256 'fps': int_or_none(src.get('frame_rate')),
257 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
258 'acodec': src.get('audio_codec'),
259 'asr': int_or_none(src.get('audio_sample_rate')),
260 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
261 'filesize': int_or_none(src.get('file_size_in_bytes')),
328f82d5 262 }
f0e83681
S
263
264 outputs = asset.get('data', {}).get('outputs')
265 if not isinstance(outputs, dict):
266 outputs = {}
267
af4116f4 268 def add_output_format_meta(f, key):
62f55aa6
S
269 output = outputs.get(key)
270 if isinstance(output, dict):
3dfceb28 271 output_format = extract_output_format(output, key)
62f55aa6
S
272 output_format.update(f)
273 return output_format
af4116f4 274 return f
62f55aa6 275
3dfceb28
S
276 def extract_formats(source_list):
277 if not isinstance(source_list, list):
278 return
279 for source in source_list:
3052a30d
S
280 video_url = url_or_none(source.get('file') or source.get('src'))
281 if not video_url:
3dfceb28 282 continue
913b61ee
S
283 if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
284 formats.extend(self._extract_m3u8_formats(
285 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
286 m3u8_id='hls', fatal=False))
287 continue
3dfceb28
S
288 format_id = source.get('label')
289 f = {
290 'url': video_url,
291 'format_id': '%sp' % format_id,
292 'height': int_or_none(format_id),
293 }
294 if format_id:
295 # Some videos contain additional metadata (e.g.
296 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
297 f = add_output_format_meta(f, format_id)
298 formats.append(f)
299
57a38a38
S
300 def extract_subtitles(track_list):
301 if not isinstance(track_list, list):
302 return
303 for track in track_list:
304 if not isinstance(track, dict):
305 continue
306 if track.get('kind') != 'captions':
307 continue
3052a30d
S
308 src = url_or_none(track.get('src'))
309 if not src:
57a38a38
S
310 continue
311 lang = track.get('language') or track.get(
312 'srclang') or track.get('label')
313 sub_dict = automatic_captions if track.get(
314 'autogenerated') is True else subtitles
315 sub_dict.setdefault(lang, []).append({
316 'url': src,
317 })
318
0ce76801
S
319 for url_kind in ('download', 'stream'):
320 urls = asset.get('%s_urls' % url_kind)
321 if isinstance(urls, dict):
322 extract_formats(urls.get('Video'))
3b35c342 323
2fbd8635
S
324 captions = asset.get('captions')
325 if isinstance(captions, list):
326 for cc in captions:
327 if not isinstance(cc, dict):
328 continue
3052a30d
S
329 cc_url = url_or_none(cc.get('url'))
330 if not cc_url:
2fbd8635
S
331 continue
332 lang = try_get(cc, lambda x: x['locale']['locale'], compat_str)
333 sub_dict = (automatic_captions if cc.get('source') == 'auto'
334 else subtitles)
335 sub_dict.setdefault(lang or 'en', []).append({
336 'url': cc_url,
337 })
338
efcba804
S
339 view_html = lecture.get('view_html')
340 if view_html:
341 view_html_urls = set()
342 for source in re.findall(r'<source[^>]+>', view_html):
343 attributes = extract_attributes(source)
344 src = attributes.get('src')
345 if not src:
346 continue
347 res = attributes.get('data-res')
348 height = int_or_none(res)
349 if src in view_html_urls:
350 continue
351 view_html_urls.add(src)
352 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
353 m3u8_formats = self._extract_m3u8_formats(
354 src, video_id, 'mp4', entry_protocol='m3u8_native',
355 m3u8_id='hls', fatal=False)
356 for f in m3u8_formats:
357 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
358 if m:
359 if not f.get('height'):
360 f['height'] = int(m.group('height'))
361 if not f.get('tbr'):
362 f['tbr'] = int(m.group('tbr'))
363 formats.extend(m3u8_formats)
364 else:
62f55aa6 365 formats.append(add_output_format_meta({
efcba804 366 'url': src,
af4116f4 367 'format_id': '%dp' % height if height else None,
efcba804 368 'height': height,
af4116f4 369 }, res))
efcba804 370
3dfceb28 371 # react rendition since 2017.04.15 (see
067aa17e 372 # https://github.com/ytdl-org/youtube-dl/issues/12744)
3dfceb28
S
373 data = self._parse_json(
374 self._search_regex(
375 r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
376 'setup data', default='{}', group='data'), video_id,
377 transform_source=unescapeHTML, fatal=False)
378 if data and isinstance(data, dict):
379 extract_formats(data.get('sources'))
380 if not duration:
381 duration = int_or_none(data.get('duration'))
57a38a38
S
382 extract_subtitles(data.get('tracks'))
383
384 if not subtitles and not automatic_captions:
385 text_tracks = self._parse_json(
386 self._search_regex(
387 r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html,
388 'text tracks', default='{}', group='data'), video_id,
389 transform_source=lambda s: js_to_json(unescapeHTML(s)),
390 fatal=False)
391 extract_subtitles(text_tracks)
3dfceb28 392
85139634
S
393 if not formats and outputs:
394 for format_id, output in outputs.items():
395 f = extract_output_format(output, format_id)
396 if f.get('url'):
397 formats.append(f)
398
8d1ddb08 399 if not formats and asset.get('course_is_drmed'):
400 self.report_drm(video_id)
401
e5de3f6c
S
402 return {
403 'id': video_id,
404 'title': title,
405 'description': description,
406 'thumbnail': thumbnail,
407 'duration': duration,
3dfceb28
S
408 'formats': formats,
409 'subtitles': subtitles,
410 'automatic_captions': automatic_captions,
e5de3f6c
S
411 }
412
413
6368e2e6 414class UdemyCourseIE(UdemyIE): # XXX: Do not subclass from concrete IE
e5de3f6c 415 IE_NAME = 'udemy:course'
d7d51389
S
416 _VALID_URL = r'https?://(?:[^/]+\.)?udemy\.com/(?P<id>[^/?#&]+)'
417 _TESTS = [{
418 'url': 'https://www.udemy.com/java-tutorial/',
419 'only_matching': True,
420 }, {
421 'url': 'https://wipro.udemy.com/java-tutorial/',
422 'only_matching': True,
423 }]
e5de3f6c
S
424
425 @classmethod
426 def suitable(cls, url):
427 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
428
429 def _real_extract(self, url):
328f82d5
S
430 course_path = self._match_id(url)
431
432 webpage = self._download_webpage(url, course_path)
e5de3f6c 433
81da8cbc 434 course_id, title = self._extract_course_info(webpage, course_path)
e5de3f6c 435
ff9d5d09 436 self._enroll_course(url, webpage, course_id)
e5de3f6c 437
6bb46007 438 response = self._download_json(
81da8cbc 439 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
6bb46007 440 course_id, 'Downloading course curriculum', query={
81da8cbc 441 'fields[chapter]': 'title,object_index',
03caa463 442 'fields[lecture]': 'title,asset',
81da8cbc
S
443 'page_size': '1000',
444 })
445
4d402db5 446 entries = []
81da8cbc
S
447 chapter, chapter_number = [None] * 2
448 for entry in response['results']:
449 clazz = entry.get('_class')
450 if clazz == 'lecture':
03caa463
S
451 asset = entry.get('asset')
452 if isinstance(asset, dict):
453 asset_type = asset.get('asset_type') or asset.get('assetType')
454 if asset_type != 'Video':
455 continue
81da8cbc
S
456 lecture_id = entry.get('id')
457 if lecture_id:
4d402db5
S
458 entry = {
459 '_type': 'url_transparent',
8d1ddb08 460 'url': smuggle_url(
461 f'https://www.udemy.com/{course_path}/learn/v4/t/lecture/{entry["id"]}',
462 {'course_id': course_id}),
81da8cbc 463 'title': entry.get('title'),
4d402db5
S
464 'ie_key': UdemyIE.ie_key(),
465 }
5bafcf65
S
466 if chapter_number:
467 entry['chapter_number'] = chapter_number
4d402db5
S
468 if chapter:
469 entry['chapter'] = chapter
470 entries.append(entry)
81da8cbc
S
471 elif clazz == 'chapter':
472 chapter_number = entry.get('object_index')
473 chapter = entry.get('title')
e5de3f6c 474
81da8cbc 475 return self.playlist_result(entries, course_id, title)