1 from __future__ import unicode_literals
5 from .common import InfoExtractor
23 class UdemyIE(InfoExtractor):
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,
56 def _extract_course_info(self, webpage, video_id):
57 course = self._parse_json(
58 unescapeHTML(self._search_regex(
59 r'ng-init=["\'].*\bcourse=({.+?});', webpage, 'course', default='{}')),
60 video_id, fatal=False) or {}
61 course_id = course.get('id') or self._search_regex(
62 (r'"id"\s*:\s*(\d+)', r'data-course-id=["\'](\d+)'),
64 return course_id, course.get('title')
66 def _enroll_course(self, base_url, webpage, course_id):
67 def combine_url(base_url, url):
68 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
70 checkout_url = unescapeHTML(self._search_regex(
71 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/payment/checkout/.+?)\1',
72 webpage, 'checkout url', group='url', default=None))
75 'Course %s is not free. You have to pay for it before you can download. '
76 'Use this URL to confirm purchase: %s'
77 % (course_id, combine_url(base_url, checkout_url)),
80 enroll_url = unescapeHTML(self._search_regex(
81 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
82 webpage, 'enroll url', group='url', default=None))
84 webpage = self._download_webpage(
85 combine_url(base_url, enroll_url),
86 course_id, 'Enrolling in the course',
87 headers={'Referer': base_url})
88 if '>You have enrolled in' in webpage:
89 self.to_screen('%s: Successfully enrolled in the course' % course_id)
91 def _download_lecture(self, course_id, lecture_id):
92 return self._download_json(
93 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?'
94 % (course_id, lecture_id),
95 lecture_id, 'Downloading lecture JSON', query={
96 'fields[lecture]': 'title,description,view_html,asset',
97 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
100 def _handle_error(self, response):
101 if not isinstance(response, dict):
103 error = response.get('error')
105 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
106 error_data = error.get('data')
108 error_str += ' - %s' % error_data.get('formErrors')
109 raise ExtractorError(error_str, expected=True)
111 def _download_json(self, url_or_request, *args, **kwargs):
113 'X-Udemy-Snail-Case': 'true',
114 'X-Requested-With': 'XMLHttpRequest',
116 for cookie in self._downloader.cookiejar:
117 if cookie.name == 'client_id':
118 headers['X-Udemy-Client-Id'] = cookie.value
119 elif cookie.name == 'access_token':
120 headers['X-Udemy-Bearer-Token'] = cookie.value
121 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
123 if isinstance(url_or_request, compat_urllib_request.Request):
124 for header, value in headers.items():
125 url_or_request.add_header(header, value)
127 url_or_request = sanitized_Request(url_or_request, headers=headers)
129 response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
130 self._handle_error(response)
133 def _real_initialize(self):
137 (username, password) = self._get_login_info()
141 login_popup = self._download_webpage(
142 self._LOGIN_URL, None, 'Downloading login popup')
144 def is_logged(webpage):
145 return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
148 if is_logged(login_popup):
151 login_form = self._form_hidden_inputs('login-form', login_popup)
155 'password': password,
158 response = self._download_webpage(
159 self._LOGIN_URL, None, 'Logging in as %s' % username,
160 data=urlencode_postdata(login_form),
162 'Referer': self._ORIGIN_URL,
163 'Origin': self._ORIGIN_URL,
166 if not is_logged(response):
167 error = self._html_search_regex(
168 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
169 response, 'error message', default=None)
171 raise ExtractorError('Unable to login: %s' % error, expected=True)
172 raise ExtractorError('Unable to log in')
174 def _real_extract(self, url):
175 lecture_id = self._match_id(url)
177 webpage = self._download_webpage(url, lecture_id)
179 course_id, _ = self._extract_course_info(webpage, lecture_id)
182 lecture = self._download_lecture(course_id, lecture_id)
183 except ExtractorError as e:
184 # Error could possibly mean we are not enrolled in the course
185 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
186 self._enroll_course(url, webpage, course_id)
187 lecture = self._download_lecture(course_id, lecture_id)
191 title = lecture['title']
192 description = lecture.get('description')
194 asset = lecture['asset']
196 asset_type = asset.get('asset_type') or asset.get('assetType')
197 if asset_type != 'Video':
198 raise ExtractorError(
199 'Lecture %s is not a video' % lecture_id, expected=True)
201 stream_url = asset.get('stream_url') or asset.get('streamUrl')
203 youtube_url = self._search_regex(
204 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
206 return self.url_result(youtube_url, 'Youtube')
208 video_id = asset['id']
209 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
210 duration = float_or_none(asset.get('data', {}).get('duration'))
214 def extract_output_format(src):
217 'format_id': '%sp' % (src.get('height') or format_id),
218 'width': int_or_none(src.get('width')),
219 'height': int_or_none(src.get('height')),
220 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
221 'vcodec': src.get('video_codec'),
222 'fps': int_or_none(src.get('frame_rate')),
223 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
224 'acodec': src.get('audio_codec'),
225 'asr': int_or_none(src.get('audio_sample_rate')),
226 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
227 'filesize': int_or_none(src.get('file_size_in_bytes')),
230 outputs = asset.get('data', {}).get('outputs')
231 if not isinstance(outputs, dict):
234 def add_output_format_meta(f, key):
235 output = outputs.get(key)
236 if isinstance(output, dict):
237 output_format = extract_output_format(output)
238 output_format.update(f)
242 download_urls = asset.get('download_urls')
243 if isinstance(download_urls, dict):
244 video = download_urls.get('Video')
245 if isinstance(video, list):
246 for format_ in video:
247 video_url = format_.get('file')
250 format_id = format_.get('label')
252 'url': format_['file'],
253 'format_id': '%sp' % format_id,
254 'height': int_or_none(format_id),
257 # Some videos contain additional metadata (e.g.
258 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
259 f = add_output_format_meta(f, format_id)
262 view_html = lecture.get('view_html')
264 view_html_urls = set()
265 for source in re.findall(r'<source[^>]+>', view_html):
266 attributes = extract_attributes(source)
267 src = attributes.get('src')
270 res = attributes.get('data-res')
271 height = int_or_none(res)
272 if src in view_html_urls:
274 view_html_urls.add(src)
275 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
276 m3u8_formats = self._extract_m3u8_formats(
277 src, video_id, 'mp4', entry_protocol='m3u8_native',
278 m3u8_id='hls', fatal=False)
279 for f in m3u8_formats:
280 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
282 if not f.get('height'):
283 f['height'] = int(m.group('height'))
285 f['tbr'] = int(m.group('tbr'))
286 formats.extend(m3u8_formats)
288 formats.append(add_output_format_meta({
290 'format_id': '%dp' % height if height else None,
294 self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
299 'description': description,
300 'thumbnail': thumbnail,
301 'duration': duration,
306 class UdemyCourseIE(UdemyIE):
307 IE_NAME = 'udemy:course'
308 _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[^/?#&]+)'
312 def suitable(cls, url):
313 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
315 def _real_extract(self, url):
316 course_path = self._match_id(url)
318 webpage = self._download_webpage(url, course_path)
320 course_id, title = self._extract_course_info(webpage, course_path)
322 self._enroll_course(url, webpage, course_id)
324 response = self._download_json(
325 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
326 course_id, 'Downloading course curriculum', query={
327 'fields[chapter]': 'title,object_index',
328 'fields[lecture]': 'title,asset',
333 chapter, chapter_number = [None] * 2
334 for entry in response['results']:
335 clazz = entry.get('_class')
336 if clazz == 'lecture':
337 asset = entry.get('asset')
338 if isinstance(asset, dict):
339 asset_type = asset.get('asset_type') or asset.get('assetType')
340 if asset_type != 'Video':
342 lecture_id = entry.get('id')
345 '_type': 'url_transparent',
346 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
347 'title': entry.get('title'),
348 'ie_key': UdemyIE.ie_key(),
351 entry['chapter_number'] = chapter_number
353 entry['chapter'] = chapter
354 entries.append(entry)
355 elif clazz == 'chapter':
356 chapter_number = entry.get('object_index')
357 chapter = entry.get('title')
359 return self.playlist_result(entries, course_id, title)