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