]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/udemy.py
[compat] Remove more functions
[yt-dlp.git] / yt_dlp / extractor / udemy.py
1 import re
2 import urllib.request
3
4 from .common import InfoExtractor
5 from ..compat import compat_HTTPError, compat_str, compat_urlparse
6 from ..utils import (
7 ExtractorError,
8 determine_ext,
9 extract_attributes,
10 float_or_none,
11 int_or_none,
12 js_to_json,
13 sanitized_Request,
14 try_get,
15 unescapeHTML,
16 url_or_none,
17 urlencode_postdata,
18 )
19
20
21 class UdemyIE(InfoExtractor):
22 IE_NAME = 'udemy'
23 _VALID_URL = r'''(?x)
24 https?://
25 (?:[^/]+\.)?udemy\.com/
26 (?:
27 [^#]+\#/lecture/|
28 lecture/view/?\?lectureId=|
29 [^/]+/learn/v4/t/lecture/
30 )
31 (?P<id>\d+)
32 '''
33 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
34 _ORIGIN_URL = 'https://www.udemy.com'
35 _NETRC_MACHINE = 'udemy'
36
37 _TESTS = [{
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',
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,
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,
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,
60 }, {
61 'url': 'https://wipro.udemy.com/java-tutorial/#/lecture/172757',
62 'only_matching': True,
63 }]
64
65 def _extract_course_info(self, webpage, video_id):
66 course = self._parse_json(
67 unescapeHTML(self._search_regex(
68 r'ng-init=["\'].*\bcourse=({.+?})[;"\']',
69 webpage, 'course', default='{}')),
70 video_id, fatal=False) or {}
71 course_id = course.get('id') or self._search_regex(
72 [
73 r'data-course-id=["\'](\d+)',
74 r'&quot;courseId&quot;\s*:\s*(\d+)'
75 ], webpage, 'course id')
76 return course_id, course.get('title')
77
78 def _enroll_course(self, base_url, webpage, course_id):
79 def combine_url(base_url, url):
80 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
81
82 checkout_url = unescapeHTML(self._search_regex(
83 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
84 webpage, 'checkout url', group='url', default=None))
85 if checkout_url:
86 raise ExtractorError(
87 'Course %s is not free. You have to pay for it before you can download. '
88 'Use this URL to confirm purchase: %s'
89 % (course_id, combine_url(base_url, checkout_url)),
90 expected=True)
91
92 enroll_url = unescapeHTML(self._search_regex(
93 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
94 webpage, 'enroll url', group='url', default=None))
95 if enroll_url:
96 webpage = self._download_webpage(
97 combine_url(base_url, enroll_url),
98 course_id, 'Enrolling in the course',
99 headers={'Referer': base_url})
100 if '>You have enrolled in' in webpage:
101 self.to_screen('%s: Successfully enrolled in the course' % course_id)
102
103 def _download_lecture(self, course_id, lecture_id):
104 return self._download_json(
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',
109 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,stream_urls,captions,data',
110 })
111
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
123 def _download_webpage_handle(self, *args, **kwargs):
124 headers = kwargs.get('headers', {}).copy()
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'
126 kwargs['headers'] = headers
127 ret = super(UdemyIE, self)._download_webpage_handle(
128 *args, **kwargs)
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 '
139 'yt-dlp with --cookies.', expected=True)
140 return ret
141
142 def _download_json(self, url_or_request, *args, **kwargs):
143 headers = {
144 'X-Udemy-Snail-Case': 'true',
145 'X-Requested-With': 'XMLHttpRequest',
146 }
147 for cookie in self.cookiejar:
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
152 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
153
154 if isinstance(url_or_request, urllib.request.Request):
155 for header, value in headers.items():
156 url_or_request.add_header(header, value)
157 else:
158 url_or_request = sanitized_Request(url_or_request, headers=headers)
159
160 response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
161 self._handle_error(response)
162 return response
163
164 def _perform_login(self, username, password):
165 login_popup = self._download_webpage(
166 self._LOGIN_URL, None, 'Downloading login popup')
167
168 def is_logged(webpage):
169 return any(re.search(p, webpage) for p in (
170 r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
171 r'>Logout<'))
172
173 # already logged in
174 if is_logged(login_popup):
175 return
176
177 login_form = self._form_hidden_inputs('login-form', login_popup)
178
179 login_form.update({
180 'email': username,
181 'password': password,
182 })
183
184 response = self._download_webpage(
185 self._LOGIN_URL, None, 'Logging in',
186 data=urlencode_postdata(login_form),
187 headers={
188 'Referer': self._ORIGIN_URL,
189 'Origin': self._ORIGIN_URL,
190 })
191
192 if not is_logged(response):
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)
198 raise ExtractorError('Unable to log in')
199
200 def _real_extract(self, url):
201 lecture_id = self._match_id(url)
202
203 webpage = self._download_webpage(url, lecture_id)
204
205 course_id, _ = self._extract_course_info(webpage, lecture_id)
206
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:
212 self._enroll_course(url, webpage, course_id)
213 lecture = self._download_lecture(course_id, lecture_id)
214 else:
215 raise
216
217 title = lecture['title']
218 description = lecture.get('description')
219
220 asset = lecture['asset']
221
222 asset_type = asset.get('asset_type') or asset.get('assetType')
223 if asset_type != 'Video':
224 raise ExtractorError(
225 'Lecture %s is not a video' % lecture_id, expected=True)
226
227 stream_url = asset.get('stream_url') or asset.get('streamUrl')
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')
233
234 video_id = compat_str(asset['id'])
235 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
236 duration = float_or_none(asset.get('data', {}).get('duration'))
237
238 subtitles = {}
239 automatic_captions = {}
240
241 formats = []
242
243 def extract_output_format(src, f_id):
244 return {
245 'url': src.get('url'),
246 'format_id': '%sp' % (src.get('height') or f_id),
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')),
257 }
258
259 outputs = asset.get('data', {}).get('outputs')
260 if not isinstance(outputs, dict):
261 outputs = {}
262
263 def add_output_format_meta(f, key):
264 output = outputs.get(key)
265 if isinstance(output, dict):
266 output_format = extract_output_format(output, key)
267 output_format.update(f)
268 return output_format
269 return f
270
271 def extract_formats(source_list):
272 if not isinstance(source_list, list):
273 return
274 for source in source_list:
275 video_url = url_or_none(source.get('file') or source.get('src'))
276 if not video_url:
277 continue
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
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
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
303 src = url_or_none(track.get('src'))
304 if not src:
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
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'))
318
319 captions = asset.get('captions')
320 if isinstance(captions, list):
321 for cc in captions:
322 if not isinstance(cc, dict):
323 continue
324 cc_url = url_or_none(cc.get('url'))
325 if not cc_url:
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
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:
360 formats.append(add_output_format_meta({
361 'url': src,
362 'format_id': '%dp' % height if height else None,
363 'height': height,
364 }, res))
365
366 # react rendition since 2017.04.15 (see
367 # https://github.com/ytdl-org/youtube-dl/issues/12744)
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'))
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)
387
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
394 self._sort_formats(formats)
395
396 return {
397 'id': video_id,
398 'title': title,
399 'description': description,
400 'thumbnail': thumbnail,
401 'duration': duration,
402 'formats': formats,
403 'subtitles': subtitles,
404 'automatic_captions': automatic_captions,
405 }
406
407
408 class UdemyCourseIE(UdemyIE):
409 IE_NAME = 'udemy:course'
410 _VALID_URL = r'https?://(?:[^/]+\.)?udemy\.com/(?P<id>[^/?#&]+)'
411 _TESTS = [{
412 'url': 'https://www.udemy.com/java-tutorial/',
413 'only_matching': True,
414 }, {
415 'url': 'https://wipro.udemy.com/java-tutorial/',
416 'only_matching': True,
417 }]
418
419 @classmethod
420 def suitable(cls, url):
421 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
422
423 def _real_extract(self, url):
424 course_path = self._match_id(url)
425
426 webpage = self._download_webpage(url, course_path)
427
428 course_id, title = self._extract_course_info(webpage, course_path)
429
430 self._enroll_course(url, webpage, course_id)
431
432 response = self._download_json(
433 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
434 course_id, 'Downloading course curriculum', query={
435 'fields[chapter]': 'title,object_index',
436 'fields[lecture]': 'title,asset',
437 'page_size': '1000',
438 })
439
440 entries = []
441 chapter, chapter_number = [None] * 2
442 for entry in response['results']:
443 clazz = entry.get('_class')
444 if clazz == 'lecture':
445 asset = entry.get('asset')
446 if isinstance(asset, dict):
447 asset_type = asset.get('asset_type') or asset.get('assetType')
448 if asset_type != 'Video':
449 continue
450 lecture_id = entry.get('id')
451 if lecture_id:
452 entry = {
453 '_type': 'url_transparent',
454 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
455 'title': entry.get('title'),
456 'ie_key': UdemyIE.ie_key(),
457 }
458 if chapter_number:
459 entry['chapter_number'] = chapter_number
460 if chapter:
461 entry['chapter'] = chapter
462 entries.append(entry)
463 elif clazz == 'chapter':
464 chapter_number = entry.get('object_index')
465 chapter = entry.get('title')
466
467 return self.playlist_result(entries, course_id, title)