1 from __future__ import unicode_literals
5 from .common import InfoExtractor
8 compat_urllib_parse_urlencode,
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,
57 def _enroll_course(self, base_url, webpage, course_id):
58 checkout_url = unescapeHTML(self._search_regex(
59 r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/payment/checkout/.+?)\1',
60 webpage, 'checkout url', group='url', default=None))
63 'Course %s is not free. You have to pay for it before you can download. '
64 'Use this URL to confirm purchase: %s' % (course_id, checkout_url), expected=True)
66 enroll_url = unescapeHTML(self._search_regex(
67 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
68 webpage, 'enroll url', group='url', default=None))
70 if not enroll_url.startswith('http'):
71 enroll_url = compat_urlparse.urljoin(base_url, enroll_url)
72 webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course')
73 if '>You have enrolled in' in webpage:
74 self.to_screen('%s: Successfully enrolled in the course' % course_id)
76 def _download_lecture(self, course_id, lecture_id):
77 return self._download_json(
78 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
79 course_id, lecture_id, compat_urllib_parse_urlencode({
80 'fields[lecture]': 'title,description,view_html,asset',
81 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
83 lecture_id, 'Downloading lecture JSON')
85 def _handle_error(self, response):
86 if not isinstance(response, dict):
88 error = response.get('error')
90 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
91 error_data = error.get('data')
93 error_str += ' - %s' % error_data.get('formErrors')
94 raise ExtractorError(error_str, expected=True)
96 def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
98 'X-Udemy-Snail-Case': 'true',
99 'X-Requested-With': 'XMLHttpRequest',
101 for cookie in self._downloader.cookiejar:
102 if cookie.name == 'client_id':
103 headers['X-Udemy-Client-Id'] = cookie.value
104 elif cookie.name == 'access_token':
105 headers['X-Udemy-Bearer-Token'] = cookie.value
106 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
108 if isinstance(url_or_request, compat_urllib_request.Request):
109 for header, value in headers.items():
110 url_or_request.add_header(header, value)
112 url_or_request = sanitized_Request(url_or_request, headers=headers)
114 response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
115 self._handle_error(response)
118 def _real_initialize(self):
122 (username, password) = self._get_login_info()
126 login_popup = self._download_webpage(
127 self._LOGIN_URL, None, 'Downloading login popup')
129 def is_logged(webpage):
130 return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
133 if is_logged(login_popup):
136 login_form = self._form_hidden_inputs('login-form', login_popup)
139 'email': username.encode('utf-8'),
140 'password': password.encode('utf-8'),
143 request = sanitized_Request(
144 self._LOGIN_URL, urlencode_postdata(login_form))
145 request.add_header('Referer', self._ORIGIN_URL)
146 request.add_header('Origin', self._ORIGIN_URL)
148 response = self._download_webpage(
149 request, None, 'Logging in as %s' % username)
151 if not is_logged(response):
152 error = self._html_search_regex(
153 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
154 response, 'error message', default=None)
156 raise ExtractorError('Unable to login: %s' % error, expected=True)
157 raise ExtractorError('Unable to log in')
159 def _real_extract(self, url):
160 lecture_id = self._match_id(url)
162 webpage = self._download_webpage(url, lecture_id)
164 course_id = self._search_regex(
165 (r'data-course-id=["\'](\d+)', r'"id"\s*:\s*(\d+)'),
166 webpage, 'course id')
169 lecture = self._download_lecture(course_id, lecture_id)
170 except ExtractorError as e:
171 # Error could possibly mean we are not enrolled in the course
172 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
173 self._enroll_course(url, webpage, course_id)
174 lecture = self._download_lecture(course_id, lecture_id)
178 title = lecture['title']
179 description = lecture.get('description')
181 asset = lecture['asset']
183 asset_type = asset.get('assetType') or asset.get('asset_type')
184 if asset_type != 'Video':
185 raise ExtractorError(
186 'Lecture %s is not a video' % lecture_id, expected=True)
188 stream_url = asset.get('streamUrl') or asset.get('stream_url')
190 youtube_url = self._search_regex(
191 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
193 return self.url_result(youtube_url, 'Youtube')
195 video_id = asset['id']
196 thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
197 duration = float_or_none(asset.get('data', {}).get('duration'))
201 def extract_output_format(src):
204 'format_id': '%sp' % (src.get('height') or format_id),
205 'width': int_or_none(src.get('width')),
206 'height': int_or_none(src.get('height')),
207 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
208 'vcodec': src.get('video_codec'),
209 'fps': int_or_none(src.get('frame_rate')),
210 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
211 'acodec': src.get('audio_codec'),
212 'asr': int_or_none(src.get('audio_sample_rate')),
213 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
214 'filesize': int_or_none(src.get('file_size_in_bytes')),
217 outputs = asset.get('data', {}).get('outputs')
218 if not isinstance(outputs, dict):
221 def add_output_format_meta(f, key, format_id):
222 output = outputs.get(key)
223 if isinstance(output, dict):
224 output_format = extract_output_format(output)
225 output_format.update(f)
228 f['format_id'] = format_id
231 download_urls = asset.get('download_urls')
232 if isinstance(download_urls, dict):
233 video = download_urls.get('Video')
234 if isinstance(video, list):
235 for format_ in video:
236 video_url = format_.get('file')
239 format_id = format_.get('label')
241 'url': format_['file'],
242 'height': int_or_none(format_id),
245 # Some videos contain additional metadata (e.g.
246 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
247 f = add_output_format_meta(f, format_id, '%sp' % format_id)
250 view_html = lecture.get('view_html')
252 view_html_urls = set()
253 for source in re.findall(r'<source[^>]+>', view_html):
254 attributes = extract_attributes(source)
255 src = attributes.get('src')
258 res = attributes.get('data-res')
259 height = int_or_none(res)
260 if src in view_html_urls:
262 view_html_urls.add(src)
263 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
264 m3u8_formats = self._extract_m3u8_formats(
265 src, video_id, 'mp4', entry_protocol='m3u8_native',
266 m3u8_id='hls', fatal=False)
267 for f in m3u8_formats:
268 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
270 if not f.get('height'):
271 f['height'] = int(m.group('height'))
273 f['tbr'] = int(m.group('tbr'))
274 formats.extend(m3u8_formats)
276 formats.append(add_output_format_meta({
279 }, res, '%dp' % height if height else None))
281 self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
286 'description': description,
287 'thumbnail': thumbnail,
288 'duration': duration,
293 class UdemyCourseIE(UdemyIE):
294 IE_NAME = 'udemy:course'
295 _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
299 def suitable(cls, url):
300 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
302 def _real_extract(self, url):
303 course_path = self._match_id(url)
305 webpage = self._download_webpage(url, course_path)
307 response = self._download_json(
308 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
309 course_path, 'Downloading course JSON')
311 course_id = response['id']
312 course_title = response.get('title')
314 self._enroll_course(url, webpage, course_id)
316 response = self._download_json(
317 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
318 course_id, 'Downloading course curriculum')
321 chapter, chapter_number = None, None
322 for asset in response:
323 asset_type = asset.get('assetType') or asset.get('asset_type')
324 if asset_type == 'Video':
325 asset_id = asset.get('id')
328 '_type': 'url_transparent',
329 'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
330 'ie_key': UdemyIE.ie_key(),
333 entry['chapter_number'] = chapter_number
335 entry['chapter'] = chapter
336 entries.append(entry)
337 elif asset.get('type') == 'chapter':
338 chapter_number = asset.get('index') or asset.get('object_index')
339 chapter = asset.get('title')
341 return self.playlist_result(entries, course_id, course_title)