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