]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/udemy.py
[extractor/youtube] Fix `uploader_id` extraction
[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 smuggle_url,
15 try_get,
16 unescapeHTML,
17 unsmuggle_url,
18 url_or_none,
19 urlencode_postdata,
20 )
21
22
23 class UdemyIE(InfoExtractor):
24 IE_NAME = 'udemy'
25 _VALID_URL = r'''(?x)
26 https?://
27 (?:[^/]+\.)?udemy\.com/
28 (?:
29 [^#]+\#/lecture/|
30 lecture/view/?\?lectureId=|
31 [^/]+/learn/v4/t/lecture/
32 )
33 (?P<id>\d+)
34 '''
35 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
36 _ORIGIN_URL = 'https://www.udemy.com'
37 _NETRC_MACHINE = 'udemy'
38
39 _TESTS = [{
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',
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,
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,
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,
62 }, {
63 'url': 'https://wipro.udemy.com/java-tutorial/#/lecture/172757',
64 'only_matching': True,
65 }]
66
67 def _extract_course_info(self, webpage, video_id):
68 course = self._parse_json(
69 unescapeHTML(self._search_regex(
70 r'ng-init=["\'].*\bcourse=({.+?})[;"\']',
71 webpage, 'course', default='{}')),
72 video_id, fatal=False) or {}
73 course_id = course.get('id') or self._search_regex(
74 [
75 r'data-course-id=["\'](\d+)',
76 r'&quot;courseId&quot;\s*:\s*(\d+)'
77 ], webpage, 'course id')
78 return course_id, course.get('title')
79
80 def _enroll_course(self, base_url, webpage, course_id):
81 def combine_url(base_url, url):
82 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
83
84 checkout_url = unescapeHTML(self._search_regex(
85 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
86 webpage, 'checkout url', group='url', default=None))
87 if checkout_url:
88 raise ExtractorError(
89 'Course %s is not free. You have to pay for it before you can download. '
90 'Use this URL to confirm purchase: %s'
91 % (course_id, combine_url(base_url, checkout_url)),
92 expected=True)
93
94 enroll_url = unescapeHTML(self._search_regex(
95 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
96 webpage, 'enroll url', group='url', default=None))
97 if enroll_url:
98 webpage = self._download_webpage(
99 combine_url(base_url, enroll_url),
100 course_id, 'Enrolling in the course',
101 headers={'Referer': base_url})
102 if '>You have enrolled in' in webpage:
103 self.to_screen('%s: Successfully enrolled in the course' % course_id)
104
105 def _download_lecture(self, course_id, lecture_id):
106 return self._download_json(
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',
111 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,stream_urls,captions,data,course_is_drmed',
112 })
113
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
125 def _download_webpage_handle(self, *args, **kwargs):
126 headers = kwargs.get('headers', {}).copy()
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'
128 kwargs['headers'] = headers
129 ret = super(UdemyIE, self)._download_webpage_handle(
130 *args, **kwargs)
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 '
141 'yt-dlp with --cookies.', expected=True)
142 return ret
143
144 def _download_json(self, url_or_request, *args, **kwargs):
145 headers = {
146 'X-Udemy-Snail-Case': 'true',
147 'X-Requested-With': 'XMLHttpRequest',
148 }
149 for cookie in self.cookiejar:
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
154 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
155
156 if isinstance(url_or_request, urllib.request.Request):
157 for header, value in headers.items():
158 url_or_request.add_header(header, value)
159 else:
160 url_or_request = sanitized_Request(url_or_request, headers=headers)
161
162 response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
163 self._handle_error(response)
164 return response
165
166 def _perform_login(self, username, password):
167 login_popup = self._download_webpage(
168 self._LOGIN_URL, None, 'Downloading login popup')
169
170 def is_logged(webpage):
171 return any(re.search(p, webpage) for p in (
172 r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
173 r'>Logout<'))
174
175 # already logged in
176 if is_logged(login_popup):
177 return
178
179 login_form = self._form_hidden_inputs('login-form', login_popup)
180
181 login_form.update({
182 'email': username,
183 'password': password,
184 })
185
186 response = self._download_webpage(
187 self._LOGIN_URL, None, 'Logging in',
188 data=urlencode_postdata(login_form),
189 headers={
190 'Referer': self._ORIGIN_URL,
191 'Origin': self._ORIGIN_URL,
192 })
193
194 if not is_logged(response):
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)
200 raise ExtractorError('Unable to log in')
201
202 def _real_extract(self, url):
203 lecture_id = self._match_id(url)
204 course_id = unsmuggle_url(url, {})[1].get('course_id')
205
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)
210
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:
216 webpage = webpage or self._download_webpage(url, lecture_id)
217 self._enroll_course(url, webpage, course_id)
218 lecture = self._download_lecture(course_id, lecture_id)
219 else:
220 raise
221
222 title = lecture['title']
223 description = lecture.get('description')
224
225 asset = lecture['asset']
226
227 asset_type = asset.get('asset_type') or asset.get('assetType')
228 if asset_type != 'Video':
229 raise ExtractorError(
230 'Lecture %s is not a video' % lecture_id, expected=True)
231
232 stream_url = asset.get('stream_url') or asset.get('streamUrl')
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')
238
239 video_id = compat_str(asset['id'])
240 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
241 duration = float_or_none(asset.get('data', {}).get('duration'))
242
243 subtitles = {}
244 automatic_captions = {}
245
246 formats = []
247
248 def extract_output_format(src, f_id):
249 return {
250 'url': src.get('url'),
251 'format_id': '%sp' % (src.get('height') or f_id),
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')),
262 }
263
264 outputs = asset.get('data', {}).get('outputs')
265 if not isinstance(outputs, dict):
266 outputs = {}
267
268 def add_output_format_meta(f, key):
269 output = outputs.get(key)
270 if isinstance(output, dict):
271 output_format = extract_output_format(output, key)
272 output_format.update(f)
273 return output_format
274 return f
275
276 def extract_formats(source_list):
277 if not isinstance(source_list, list):
278 return
279 for source in source_list:
280 video_url = url_or_none(source.get('file') or source.get('src'))
281 if not video_url:
282 continue
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
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
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
308 src = url_or_none(track.get('src'))
309 if not src:
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
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'))
323
324 captions = asset.get('captions')
325 if isinstance(captions, list):
326 for cc in captions:
327 if not isinstance(cc, dict):
328 continue
329 cc_url = url_or_none(cc.get('url'))
330 if not cc_url:
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
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:
365 formats.append(add_output_format_meta({
366 'url': src,
367 'format_id': '%dp' % height if height else None,
368 'height': height,
369 }, res))
370
371 # react rendition since 2017.04.15 (see
372 # https://github.com/ytdl-org/youtube-dl/issues/12744)
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'))
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)
392
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
399 if not formats and asset.get('course_is_drmed'):
400 self.report_drm(video_id)
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): # XXX: Do not subclass from concrete IE
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': smuggle_url(
461 f'https://www.udemy.com/{course_path}/learn/v4/t/lecture/{entry["id"]}',
462 {'course_id': course_id}),
463 'title': entry.get('title'),
464 'ie_key': UdemyIE.ie_key(),
465 }
466 if chapter_number:
467 entry['chapter_number'] = chapter_number
468 if chapter:
469 entry['chapter'] = chapter
470 entries.append(entry)
471 elif clazz == 'chapter':
472 chapter_number = entry.get('object_index')
473 chapter = entry.get('title')
474
475 return self.playlist_result(entries, course_id, title)