1 from __future__ import unicode_literals
5 from .common import InfoExtractor
24 class UdemyIE(InfoExtractor):
31 lecture/view/?\?lectureId=|
32 [^/]+/learn/v4/t/lecture/
36 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
37 _ORIGIN_URL = 'https://www.udemy.com'
38 _NETRC_MACHINE = 'udemy'
41 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
42 'md5': '98eda5b657e752cf945d8445e261b5c5',
46 'title': 'Introduction and Installation',
47 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
50 'skip': 'Requires udemy account credentials',
53 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
54 'only_matching': True,
56 # no url in outputs format entry
57 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812',
58 'only_matching': True,
61 def _extract_course_info(self, webpage, video_id):
62 course = self._parse_json(
63 unescapeHTML(self._search_regex(
64 r'ng-init=["\'].*\bcourse=({.+?});', webpage, 'course', default='{}')),
65 video_id, fatal=False) or {}
66 course_id = course.get('id') or self._search_regex(
67 (r'"id"\s*:\s*(\d+)', r'data-course-id=["\'](\d+)'),
69 return course_id, course.get('title')
71 def _enroll_course(self, base_url, webpage, course_id):
72 def combine_url(base_url, url):
73 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
75 checkout_url = unescapeHTML(self._search_regex(
76 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/payment/checkout/.+?)\1',
77 webpage, 'checkout url', group='url', default=None))
80 'Course %s is not free. You have to pay for it before you can download. '
81 'Use this URL to confirm purchase: %s'
82 % (course_id, combine_url(base_url, checkout_url)),
85 enroll_url = unescapeHTML(self._search_regex(
86 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
87 webpage, 'enroll url', group='url', default=None))
89 webpage = self._download_webpage(
90 combine_url(base_url, enroll_url),
91 course_id, 'Enrolling in the course',
92 headers={'Referer': base_url})
93 if '>You have enrolled in' in webpage:
94 self.to_screen('%s: Successfully enrolled in the course' % course_id)
96 def _download_lecture(self, course_id, lecture_id):
97 return self._download_json(
98 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?'
99 % (course_id, lecture_id),
100 lecture_id, 'Downloading lecture JSON', query={
101 'fields[lecture]': 'title,description,view_html,asset',
102 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
105 def _handle_error(self, response):
106 if not isinstance(response, dict):
108 error = response.get('error')
110 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
111 error_data = error.get('data')
113 error_str += ' - %s' % error_data.get('formErrors')
114 raise ExtractorError(error_str, expected=True)
116 def _download_json(self, url_or_request, *args, **kwargs):
118 'X-Udemy-Snail-Case': 'true',
119 'X-Requested-With': 'XMLHttpRequest',
121 for cookie in self._downloader.cookiejar:
122 if cookie.name == 'client_id':
123 headers['X-Udemy-Client-Id'] = cookie.value
124 elif cookie.name == 'access_token':
125 headers['X-Udemy-Bearer-Token'] = cookie.value
126 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
128 if isinstance(url_or_request, compat_urllib_request.Request):
129 for header, value in headers.items():
130 url_or_request.add_header(header, value)
132 url_or_request = sanitized_Request(url_or_request, headers=headers)
134 response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
135 self._handle_error(response)
138 def _real_initialize(self):
142 (username, password) = self._get_login_info()
146 login_popup = self._download_webpage(
147 self._LOGIN_URL, None, 'Downloading login popup')
149 def is_logged(webpage):
150 return any(re.search(p, webpage) for p in (
151 r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
155 if is_logged(login_popup):
158 login_form = self._form_hidden_inputs('login-form', login_popup)
162 'password': password,
165 response = self._download_webpage(
166 self._LOGIN_URL, None, 'Logging in as %s' % username,
167 data=urlencode_postdata(login_form),
169 'Referer': self._ORIGIN_URL,
170 'Origin': self._ORIGIN_URL,
173 if not is_logged(response):
174 error = self._html_search_regex(
175 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
176 response, 'error message', default=None)
178 raise ExtractorError('Unable to login: %s' % error, expected=True)
179 raise ExtractorError('Unable to log in')
181 def _real_extract(self, url):
182 lecture_id = self._match_id(url)
184 webpage = self._download_webpage(url, lecture_id)
186 course_id, _ = self._extract_course_info(webpage, lecture_id)
189 lecture = self._download_lecture(course_id, lecture_id)
190 except ExtractorError as e:
191 # Error could possibly mean we are not enrolled in the course
192 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
193 self._enroll_course(url, webpage, course_id)
194 lecture = self._download_lecture(course_id, lecture_id)
198 title = lecture['title']
199 description = lecture.get('description')
201 asset = lecture['asset']
203 asset_type = asset.get('asset_type') or asset.get('assetType')
204 if asset_type != 'Video':
205 raise ExtractorError(
206 'Lecture %s is not a video' % lecture_id, expected=True)
208 stream_url = asset.get('stream_url') or asset.get('streamUrl')
210 youtube_url = self._search_regex(
211 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
213 return self.url_result(youtube_url, 'Youtube')
215 video_id = compat_str(asset['id'])
216 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
217 duration = float_or_none(asset.get('data', {}).get('duration'))
220 automatic_captions = {}
224 def extract_output_format(src, f_id):
226 'url': src.get('url'),
227 'format_id': '%sp' % (src.get('height') or f_id),
228 'width': int_or_none(src.get('width')),
229 'height': int_or_none(src.get('height')),
230 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
231 'vcodec': src.get('video_codec'),
232 'fps': int_or_none(src.get('frame_rate')),
233 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
234 'acodec': src.get('audio_codec'),
235 'asr': int_or_none(src.get('audio_sample_rate')),
236 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
237 'filesize': int_or_none(src.get('file_size_in_bytes')),
240 outputs = asset.get('data', {}).get('outputs')
241 if not isinstance(outputs, dict):
244 def add_output_format_meta(f, key):
245 output = outputs.get(key)
246 if isinstance(output, dict):
247 output_format = extract_output_format(output, key)
248 output_format.update(f)
252 def extract_formats(source_list):
253 if not isinstance(source_list, list):
255 for source in source_list:
256 video_url = source.get('file') or source.get('src')
257 if not video_url or not isinstance(video_url, compat_str):
259 format_id = source.get('label')
262 'format_id': '%sp' % format_id,
263 'height': int_or_none(format_id),
266 # Some videos contain additional metadata (e.g.
267 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
268 f = add_output_format_meta(f, format_id)
271 download_urls = asset.get('download_urls')
272 if isinstance(download_urls, dict):
273 extract_formats(download_urls.get('Video'))
275 view_html = lecture.get('view_html')
277 view_html_urls = set()
278 for source in re.findall(r'<source[^>]+>', view_html):
279 attributes = extract_attributes(source)
280 src = attributes.get('src')
283 res = attributes.get('data-res')
284 height = int_or_none(res)
285 if src in view_html_urls:
287 view_html_urls.add(src)
288 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
289 m3u8_formats = self._extract_m3u8_formats(
290 src, video_id, 'mp4', entry_protocol='m3u8_native',
291 m3u8_id='hls', fatal=False)
292 for f in m3u8_formats:
293 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
295 if not f.get('height'):
296 f['height'] = int(m.group('height'))
298 f['tbr'] = int(m.group('tbr'))
299 formats.extend(m3u8_formats)
301 formats.append(add_output_format_meta({
303 'format_id': '%dp' % height if height else None,
307 # react rendition since 2017.04.15 (see
308 # https://github.com/rg3/youtube-dl/issues/12744)
309 data = self._parse_json(
311 r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
312 'setup data', default='{}', group='data'), video_id,
313 transform_source=unescapeHTML, fatal=False)
314 if data and isinstance(data, dict):
315 extract_formats(data.get('sources'))
317 duration = int_or_none(data.get('duration'))
318 tracks = data.get('tracks')
319 if isinstance(tracks, list):
321 if not isinstance(track, dict):
323 if track.get('kind') != 'captions':
325 src = track.get('src')
326 if not src or not isinstance(src, compat_str):
328 lang = track.get('language') or track.get(
329 'srclang') or track.get('label')
330 sub_dict = automatic_captions if track.get(
331 'autogenerated') is True else subtitles
332 sub_dict.setdefault(lang, []).append({
336 self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
341 'description': description,
342 'thumbnail': thumbnail,
343 'duration': duration,
345 'subtitles': subtitles,
346 'automatic_captions': automatic_captions,
350 class UdemyCourseIE(UdemyIE):
351 IE_NAME = 'udemy:course'
352 _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'
356 def suitable(cls, url):
357 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
359 def _real_extract(self, url):
360 course_path = self._match_id(url)
362 webpage = self._download_webpage(url, course_path)
364 course_id, title = self._extract_course_info(webpage, course_path)
366 self._enroll_course(url, webpage, course_id)
368 response = self._download_json(
369 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
370 course_id, 'Downloading course curriculum', query={
371 'fields[chapter]': 'title,object_index',
372 'fields[lecture]': 'title,asset',
377 chapter, chapter_number = [None] * 2
378 for entry in response['results']:
379 clazz = entry.get('_class')
380 if clazz == 'lecture':
381 asset = entry.get('asset')
382 if isinstance(asset, dict):
383 asset_type = asset.get('asset_type') or asset.get('assetType')
384 if asset_type != 'Video':
386 lecture_id = entry.get('id')
389 '_type': 'url_transparent',
390 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
391 'title': entry.get('title'),
392 'ie_key': UdemyIE.ie_key(),
395 entry['chapter_number'] = chapter_number
397 entry['chapter'] = chapter
398 entries.append(entry)
399 elif clazz == 'chapter':
400 chapter_number = entry.get('object_index')
401 chapter = entry.get('title')
403 return self.playlist_result(entries, course_id, title)