]>
jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/udemy.py
4 from .common
import InfoExtractor
5 from ..compat
import compat_HTTPError
, compat_str
, compat_urlparse
23 class UdemyIE(InfoExtractor
):
27 (?:[^/]+\.)?udemy\.com/
30 lecture/view/?\?lectureId=|
31 [^/]+/learn/v4/t/lecture/
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'
40 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
41 'md5': '98eda5b657e752cf945d8445e261b5c5',
45 'title': 'Introduction and Installation',
46 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
49 'skip': 'Requires udemy account credentials',
52 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
53 'only_matching': True,
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,
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,
63 'url': 'https://wipro.udemy.com/java-tutorial/#/lecture/172757',
64 'only_matching': True,
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(
75 r'data-course-id=["\'](\d
+)',
76 r'"
;courseId
"
;\s
*:\s
*(\d
+)'
77 ], webpage, 'course
id')
78 return course_id, course.get('title
')
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
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))
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)),
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))
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)
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
',
114 def _handle_error(self, response):
115 if not isinstance(response, dict):
117 error = response.get('error
')
119 error_str = 'Udemy returned error
#%s: %s' % (error.get('code'), error.get('message'))
120 error_data
= error
.get('data')
122 error_str
+= ' - %s' % error_data
.get('formErrors')
123 raise ExtractorError(error_str
, expected
=True)
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
(
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',
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)
144 def _download_json(self
, url_or_request
, *args
, **kwargs
):
146 'X-Udemy-Snail-Case': 'true',
147 'X-Requested-With': 'XMLHttpRequest',
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
156 if isinstance(url_or_request
, urllib
.request
.Request
):
157 for header
, value
in headers
.items():
158 url_or_request
.add_header(header
, value
)
160 url_or_request
= sanitized_Request(url_or_request
, headers
=headers
)
162 response
= super(UdemyIE
, self
)._download
_json
(url_or_request
, *args
, **kwargs
)
163 self
._handle
_error
(response
)
166 def _perform_login(self
, username
, password
):
167 login_popup
= self
._download
_webpage
(
168 self
._LOGIN
_URL
, None, 'Downloading login popup')
170 def is_logged(webpage
):
171 return any(re
.search(p
, webpage
) for p
in (
172 r
'href=["\'](?
:https
://www\
.udemy\
.com
)?
/user
/logout
/',
176 if is_logged(login_popup):
179 login_form = self._form_hidden_inputs('login
-form
', login_popup)
183 'password
': password,
186 response = self._download_webpage(
187 self._LOGIN_URL, None, 'Logging
in',
188 data=urlencode_postdata(login_form),
190 'Referer
': self._ORIGIN_URL,
191 'Origin
': self._ORIGIN_URL,
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)
199 raise ExtractorError('Unable to login: %s' % error, expected=True)
200 raise ExtractorError('Unable to log in')
202 def _real_extract(self, url):
203 lecture_id = self._match_id(url)
204 course_id = unsmuggle_url(url, {})[1].get('course_id')
208 webpage = self._download_webpage(url, lecture_id)
209 course_id, _ = self._extract_course_info(webpage, lecture_id)
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)
222 title = lecture['title']
223 description = lecture.get('description')
225 asset = lecture['asset']
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)
232 stream_url = asset.get('stream_url') or asset.get('streamUrl')
234 youtube_url = self._search_regex(
235 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
237 return self.url_result(youtube_url, 'Youtube')
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'))
244 automatic_captions = {}
248 def extract_output_format(src, f_id):
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')),
264 outputs = asset.get('data', {}).get('outputs')
265 if not isinstance(outputs, dict):
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)
276 def extract_formats(source_list):
277 if not isinstance(source_list, list):
279 for source in source_list:
280 video_url = url_or_none(source.get('file') or source.get('src'))
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))
288 format_id = source.get('label')
291 'format_id': '%sp' % format_id,
292 'height': int_or_none(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)
300 def extract_subtitles(track_list):
301 if not isinstance(track_list, list):
303 for track in track_list:
304 if not isinstance(track, dict):
306 if track.get('kind') != 'captions':
308 src = url_or_none(track.get('src'))
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({
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'))
324 captions = asset.get('captions')
325 if isinstance(captions, list):
327 if not isinstance(cc, dict):
329 cc_url = url_or_none(cc.get('url'))
332 lang = try_get(cc, lambda x: x['locale']['locale'], compat_str)
333 sub_dict = (automatic_captions if cc.get('source') == 'auto'
335 sub_dict.setdefault(lang or 'en', []).append({
339 view_html = lecture.get('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')
347 res = attributes.get('data-res')
348 height = int_or_none(res)
349 if src in view_html_urls:
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'])
359 if not f.get('height'):
360 f['height'] = int(m.group('height'))
362 f['tbr'] = int(m.group('tbr'))
363 formats.extend(m3u8_formats)
365 formats.append(add_output_format_meta({
367 'format_id': '%dp' % height if height else None,
371 # react rendition since 2017.04.15 (see
372 # https://github.com/ytdl-org/youtube-dl/issues/12744)
373 data = self._parse_json(
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
'))
381 duration = int_or_none(data.get('duration
'))
382 extract_subtitles(data.get('tracks
'))
384 if not subtitles and not automatic_captions:
385 text_tracks = self._parse_json(
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)),
391 extract_subtitles(text_tracks)
393 if not formats and outputs:
394 for format_id, output in outputs.items():
395 f = extract_output_format(output, format_id)
399 if not formats and asset.get('course_is_drmed'):
400 self.report_drm(video_id)
405 'description': description,
406 'thumbnail': thumbnail,
407 'duration': duration,
409 'subtitles': subtitles,
410 'automatic_captions': automatic_captions,
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>[^/?#&]+)'
418 'url': 'https://www.udemy.com/java-tutorial/',
419 'only_matching': True,
421 'url': 'https://wipro.udemy.com/java-tutorial/',
422 'only_matching': True,
426 def suitable(cls, url):
427 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
429 def _real_extract(self, url):
430 course_path = self._match_id(url)
432 webpage = self._download_webpage(url, course_path)
434 course_id, title = self._extract_course_info(webpage, course_path)
436 self._enroll_course(url, webpage, course_id)
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',
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':
456 lecture_id = entry.get('id')
459 '_type': 'url_transparent',
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(),
467 entry['chapter_number'] = chapter_number
469 entry['chapter'] = chapter
470 entries.append(entry)
471 elif clazz == 'chapter':
472 chapter_number = entry.get('object_index')
473 chapter = entry.get('title')
475 return self.playlist_result(entries, course_id, title)