1 from __future__ import unicode_literals
3 from .common import InfoExtractor
18 class UdemyIE(InfoExtractor):
20 _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
21 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
22 _ORIGIN_URL = 'https://www.udemy.com'
23 _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
24 _ALREADY_ENROLLED = '>You are already taking this course.<'
25 _NETRC_MACHINE = 'udemy'
28 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
29 'md5': '98eda5b657e752cf945d8445e261b5c5',
33 'title': 'Introduction and Installation',
34 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
37 'skip': 'Requires udemy account credentials',
40 def _enroll_course(self, webpage, course_id):
41 enroll_url = self._search_regex(
42 r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/course/subscribe/.+?)\1',
43 webpage, 'enroll url', group='url',
44 default='https://www.udemy.com/course/subscribe/?courseId=%s' % course_id)
45 webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course')
46 if self._SUCCESSFULLY_ENROLLED in webpage:
47 self.to_screen('%s: Successfully enrolled in' % course_id)
48 elif self._ALREADY_ENROLLED in webpage:
49 self.to_screen('%s: Already enrolled in' % course_id)
51 def _download_lecture(self, course_id, lecture_id):
52 return self._download_json(
53 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
54 course_id, lecture_id, compat_urllib_parse.urlencode({
57 'fields[lecture]': 'title,description,asset',
58 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
59 'instructorPreviewMode': 'False',
61 lecture_id, 'Downloading lecture JSON', fatal=False)
63 def _handle_error(self, response):
64 if not isinstance(response, dict):
66 error = response.get('error')
68 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
69 error_data = error.get('data')
71 error_str += ' - %s' % error_data.get('formErrors')
72 raise ExtractorError(error_str, expected=True)
74 def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata', *args, **kwargs):
76 'X-Udemy-Snail-Case': 'true',
77 'X-Requested-With': 'XMLHttpRequest',
79 for cookie in self._downloader.cookiejar:
80 if cookie.name == 'client_id':
81 headers['X-Udemy-Client-Id'] = cookie.value
82 elif cookie.name == 'access_token':
83 headers['X-Udemy-Bearer-Token'] = cookie.value
84 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
86 if isinstance(url_or_request, compat_urllib_request.Request):
87 for header, value in headers.items():
88 url_or_request.add_header(header, value)
90 url_or_request = sanitized_Request(url_or_request, headers=headers)
92 response = super(UdemyIE, self)._download_json(url_or_request, video_id, note, *args, **kwargs)
93 self._handle_error(response)
96 def _real_initialize(self):
100 (username, password) = self._get_login_info()
104 login_popup = self._download_webpage(
105 self._LOGIN_URL, None, 'Downloading login popup')
107 def is_logged(webpage):
108 return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
111 if is_logged(login_popup):
114 login_form = self._form_hidden_inputs('login-form', login_popup)
117 'email': username.encode('utf-8'),
118 'password': password.encode('utf-8'),
121 request = sanitized_Request(
122 self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
123 request.add_header('Referer', self._ORIGIN_URL)
124 request.add_header('Origin', self._ORIGIN_URL)
126 response = self._download_webpage(
127 request, None, 'Logging in as %s' % username)
129 if not is_logged(response):
130 error = self._html_search_regex(
131 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
132 response, 'error message', default=None)
134 raise ExtractorError('Unable to login: %s' % error, expected=True)
135 raise ExtractorError('Unable to log in')
137 def _real_extract(self, url):
138 lecture_id = self._match_id(url)
140 webpage = self._download_webpage(url, lecture_id)
142 course_id = self._search_regex(
143 r'data-course-id=["\'](\d+)', webpage, 'course id')
146 lecture = self._download_lecture(course_id, lecture_id)
147 except ExtractorError as e:
148 # Error could possibly mean we are not enrolled in the course
149 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
150 self._enroll_course(webpage, course_id)
151 lecture_id = self._download_lecture(course_id, lecture_id)
155 title = lecture['title']
156 description = lecture.get('description')
158 asset = lecture['asset']
160 asset_type = asset.get('assetType') or asset.get('asset_type')
161 if asset_type != 'Video':
162 raise ExtractorError(
163 'Lecture %s is not a video' % lecture_id, expected=True)
165 stream_url = asset.get('streamUrl') or asset.get('stream_url')
167 youtube_url = self._search_regex(
168 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
170 return self.url_result(youtube_url, 'Youtube')
172 video_id = asset['id']
173 thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
174 duration = float_or_none(asset.get('data', {}).get('duration'))
175 outputs = asset.get('data', {}).get('outputs', {})
178 for format_ in asset.get('download_urls', {}).get('Video', []):
179 video_url = format_.get('file')
182 format_id = format_.get('label')
184 'url': format_['file'],
185 'height': int_or_none(format_id),
188 # Some videos contain additional metadata (e.g.
189 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
190 output = outputs.get(format_id)
191 if isinstance(output, dict):
193 'format_id': '%sp' % (output.get('label') or format_id),
194 'width': int_or_none(output.get('width')),
195 'height': int_or_none(output.get('height')),
196 'vbr': int_or_none(output.get('video_bitrate_in_kbps')),
197 'vcodec': output.get('video_codec'),
198 'fps': int_or_none(output.get('frame_rate')),
199 'abr': int_or_none(output.get('audio_bitrate_in_kbps')),
200 'acodec': output.get('audio_codec'),
201 'asr': int_or_none(output.get('audio_sample_rate')),
202 'tbr': int_or_none(output.get('total_bitrate_in_kbps')),
203 'filesize': int_or_none(output.get('file_size_in_bytes')),
206 f['format_id'] = '%sp' % format_id
209 self._sort_formats(formats)
214 'description': description,
215 'thumbnail': thumbnail,
216 'duration': duration,
221 class UdemyCourseIE(UdemyIE):
222 IE_NAME = 'udemy:course'
223 _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
227 def suitable(cls, url):
228 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
230 def _real_extract(self, url):
231 course_path = self._match_id(url)
233 webpage = self._download_webpage(url, course_path)
235 response = self._download_json(
236 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
237 course_path, 'Downloading course JSON')
239 course_id = response['id']
240 course_title = response.get('title')
242 self._enroll_course(webpage, course_id)
244 response = self._download_json(
245 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
246 course_id, 'Downloading course curriculum')
250 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
251 for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
254 return self.playlist_result(entries, course_id, course_title)