1 from __future__ import unicode_literals
3 from .common import InfoExtractor
17 class UdemyIE(InfoExtractor):
19 _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)'
20 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
21 _ORIGIN_URL = 'https://www.udemy.com'
22 _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
23 _ALREADY_ENROLLED = '>You are already taking this course.<'
24 _NETRC_MACHINE = 'udemy'
27 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
28 'md5': '98eda5b657e752cf945d8445e261b5c5',
32 'title': 'Introduction and Installation',
33 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
36 'skip': 'Requires udemy account credentials',
39 def _enroll_course(self, webpage, course_id):
40 enroll_url = self._search_regex(
41 r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/course/subscribe/.+?)\1',
42 webpage, 'enroll url', group='url',
43 default='https://www.udemy.com/course/subscribe/?courseId=%s' % course_id)
44 webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course')
45 if self._SUCCESSFULLY_ENROLLED in webpage:
46 self.to_screen('%s: Successfully enrolled in' % course_id)
47 elif self._ALREADY_ENROLLED in webpage:
48 self.to_screen('%s: Already enrolled in' % course_id)
50 def _download_lecture(self, course_id, lecture_id):
51 return self._download_json(
52 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
53 course_id, lecture_id, compat_urllib_parse.urlencode({
56 'fields[lecture]': 'title,description,asset',
57 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
58 'instructorPreviewMode': 'False',
60 lecture_id, 'Downloading lecture JSON')
62 def _handle_error(self, response):
63 if not isinstance(response, dict):
65 error = response.get('error')
67 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
68 error_data = error.get('data')
70 error_str += ' - %s' % error_data.get('formErrors')
71 raise ExtractorError(error_str, expected=True)
73 def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
75 'X-Udemy-Snail-Case': 'true',
76 'X-Requested-With': 'XMLHttpRequest',
78 for cookie in self._downloader.cookiejar:
79 if cookie.name == 'client_id':
80 headers['X-Udemy-Client-Id'] = cookie.value
81 elif cookie.name == 'access_token':
82 headers['X-Udemy-Bearer-Token'] = cookie.value
83 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
85 if isinstance(url_or_request, compat_urllib_request.Request):
86 for header, value in headers.items():
87 url_or_request.add_header(header, value)
89 url_or_request = sanitized_Request(url_or_request, headers=headers)
91 response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
92 self._handle_error(response)
95 def _real_initialize(self):
99 (username, password) = self._get_login_info()
103 login_popup = self._download_webpage(
104 self._LOGIN_URL, None, 'Downloading login popup')
106 def is_logged(webpage):
107 return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
110 if is_logged(login_popup):
113 login_form = self._form_hidden_inputs('login-form', login_popup)
116 'email': username.encode('utf-8'),
117 'password': password.encode('utf-8'),
120 request = sanitized_Request(
121 self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
122 request.add_header('Referer', self._ORIGIN_URL)
123 request.add_header('Origin', self._ORIGIN_URL)
125 response = self._download_webpage(
126 request, None, 'Logging in as %s' % username)
128 if not is_logged(response):
129 error = self._html_search_regex(
130 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
131 response, 'error message', default=None)
133 raise ExtractorError('Unable to login: %s' % error, expected=True)
134 raise ExtractorError('Unable to log in')
136 def _real_extract(self, url):
137 lecture_id = self._match_id(url)
139 webpage = self._download_webpage(url, lecture_id)
141 course_id = self._search_regex(
142 r'data-course-id=["\'](\d+)', webpage, 'course id')
145 lecture = self._download_lecture(course_id, lecture_id)
146 except ExtractorError as e:
147 # Error could possibly mean we are not enrolled in the course
148 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
149 self._enroll_course(webpage, course_id)
150 lecture_id = self._download_lecture(course_id, lecture_id)
154 title = lecture['title']
155 description = lecture.get('description')
157 asset = lecture['asset']
159 asset_type = asset.get('assetType') or asset.get('asset_type')
160 if asset_type != 'Video':
161 raise ExtractorError(
162 'Lecture %s is not a video' % lecture_id, expected=True)
164 stream_url = asset.get('streamUrl') or asset.get('stream_url')
166 youtube_url = self._search_regex(
167 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
169 return self.url_result(youtube_url, 'Youtube')
171 video_id = asset['id']
172 thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
173 duration = float_or_none(asset.get('data', {}).get('duration'))
174 outputs = asset.get('data', {}).get('outputs', {})
177 for format_ in asset.get('download_urls', {}).get('Video', []):
178 video_url = format_.get('file')
181 format_id = format_.get('label')
183 'url': format_['file'],
184 'height': int_or_none(format_id),
187 # Some videos contain additional metadata (e.g.
188 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
189 output = outputs.get(format_id)
190 if isinstance(output, dict):
192 'format_id': '%sp' % (output.get('label') or format_id),
193 'width': int_or_none(output.get('width')),
194 'height': int_or_none(output.get('height')),
195 'vbr': int_or_none(output.get('video_bitrate_in_kbps')),
196 'vcodec': output.get('video_codec'),
197 'fps': int_or_none(output.get('frame_rate')),
198 'abr': int_or_none(output.get('audio_bitrate_in_kbps')),
199 'acodec': output.get('audio_codec'),
200 'asr': int_or_none(output.get('audio_sample_rate')),
201 'tbr': int_or_none(output.get('total_bitrate_in_kbps')),
202 'filesize': int_or_none(output.get('file_size_in_bytes')),
205 f['format_id'] = '%sp' % format_id
208 self._sort_formats(formats)
213 'description': description,
214 'thumbnail': thumbnail,
215 'duration': duration,
220 class UdemyCourseIE(UdemyIE):
221 IE_NAME = 'udemy:course'
222 _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
226 def suitable(cls, url):
227 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
229 def _real_extract(self, url):
230 course_path = self._match_id(url)
232 webpage = self._download_webpage(url, course_path)
234 response = self._download_json(
235 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
236 course_path, 'Downloading course JSON')
238 course_id = response['id']
239 course_title = response.get('title')
241 self._enroll_course(webpage, course_id)
243 response = self._download_json(
244 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
245 course_id, 'Downloading course curriculum')
249 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
250 for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
253 return self.playlist_result(entries, course_id, course_title)