1 from __future__ import unicode_literals
3 from .common import InfoExtractor
19 class UdemyIE(InfoExtractor):
26 lecture/view/?\?lectureId=|
27 [^/]+/learn/v4/t/lecture/
31 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
32 _ORIGIN_URL = 'https://www.udemy.com'
33 _NETRC_MACHINE = 'udemy'
36 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
37 'md5': '98eda5b657e752cf945d8445e261b5c5',
41 'title': 'Introduction and Installation',
42 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
45 'skip': 'Requires udemy account credentials',
48 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
49 'only_matching': True,
52 def _enroll_course(self, base_url, webpage, course_id):
53 checkout_url = unescapeHTML(self._search_regex(
54 r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/payment/checkout/.+?)\1',
55 webpage, 'checkout url', group='url', default=None))
58 'Course %s is not free. You have to pay for it before you can download. '
59 'Use this URL to confirm purchase: %s' % (course_id, checkout_url), expected=True)
61 enroll_url = unescapeHTML(self._search_regex(
62 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
63 webpage, 'enroll url', group='url', default=None))
65 if not enroll_url.startswith('http'):
66 enroll_url = compat_urlparse.urljoin(base_url, enroll_url)
67 webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course')
68 if '>You have enrolled in' in webpage:
69 self.to_screen('%s: Successfully enrolled in the course' % course_id)
71 def _download_lecture(self, course_id, lecture_id):
72 return self._download_json(
73 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
74 course_id, lecture_id, compat_urllib_parse.urlencode({
77 'fields[lecture]': 'title,description,asset',
78 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
79 'instructorPreviewMode': 'False',
81 lecture_id, 'Downloading lecture JSON')
83 def _handle_error(self, response):
84 if not isinstance(response, dict):
86 error = response.get('error')
88 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
89 error_data = error.get('data')
91 error_str += ' - %s' % error_data.get('formErrors')
92 raise ExtractorError(error_str, expected=True)
94 def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
96 'X-Udemy-Snail-Case': 'true',
97 'X-Requested-With': 'XMLHttpRequest',
99 for cookie in self._downloader.cookiejar:
100 if cookie.name == 'client_id':
101 headers['X-Udemy-Client-Id'] = cookie.value
102 elif cookie.name == 'access_token':
103 headers['X-Udemy-Bearer-Token'] = cookie.value
104 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
106 if isinstance(url_or_request, compat_urllib_request.Request):
107 for header, value in headers.items():
108 url_or_request.add_header(header, value)
110 url_or_request = sanitized_Request(url_or_request, headers=headers)
112 response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
113 self._handle_error(response)
116 def _real_initialize(self):
120 (username, password) = self._get_login_info()
124 login_popup = self._download_webpage(
125 self._LOGIN_URL, None, 'Downloading login popup')
127 def is_logged(webpage):
128 return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
131 if is_logged(login_popup):
134 login_form = self._form_hidden_inputs('login-form', login_popup)
137 'email': username.encode('utf-8'),
138 'password': password.encode('utf-8'),
141 request = sanitized_Request(
142 self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
143 request.add_header('Referer', self._ORIGIN_URL)
144 request.add_header('Origin', self._ORIGIN_URL)
146 response = self._download_webpage(
147 request, None, 'Logging in as %s' % username)
149 if not is_logged(response):
150 error = self._html_search_regex(
151 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
152 response, 'error message', default=None)
154 raise ExtractorError('Unable to login: %s' % error, expected=True)
155 raise ExtractorError('Unable to log in')
157 def _real_extract(self, url):
158 lecture_id = self._match_id(url)
160 webpage = self._download_webpage(url, lecture_id)
162 course_id = self._search_regex(
163 (r'data-course-id=["\'](\d+)', r'"id"\s*:\s*(\d+)'),
164 webpage, 'course id')
167 lecture = self._download_lecture(course_id, lecture_id)
168 except ExtractorError as e:
169 # Error could possibly mean we are not enrolled in the course
170 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
171 self._enroll_course(url, webpage, course_id)
172 lecture = self._download_lecture(course_id, lecture_id)
176 title = lecture['title']
177 description = lecture.get('description')
179 asset = lecture['asset']
181 asset_type = asset.get('assetType') or asset.get('asset_type')
182 if asset_type != 'Video':
183 raise ExtractorError(
184 'Lecture %s is not a video' % lecture_id, expected=True)
186 stream_url = asset.get('streamUrl') or asset.get('stream_url')
188 youtube_url = self._search_regex(
189 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
191 return self.url_result(youtube_url, 'Youtube')
193 video_id = asset['id']
194 thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
195 duration = float_or_none(asset.get('data', {}).get('duration'))
199 def extract_output_format(src):
202 'format_id': '%sp' % (src.get('label') or format_id),
203 'width': int_or_none(src.get('width')),
204 'height': int_or_none(src.get('height')),
205 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
206 'vcodec': src.get('video_codec'),
207 'fps': int_or_none(src.get('frame_rate')),
208 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
209 'acodec': src.get('audio_codec'),
210 'asr': int_or_none(src.get('audio_sample_rate')),
211 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
212 'filesize': int_or_none(src.get('file_size_in_bytes')),
215 outputs = asset.get('data', {}).get('outputs')
216 if not isinstance(outputs, dict):
219 for format_id, output in outputs.items():
220 if isinstance(output, dict) and output.get('url'):
221 formats.append(extract_output_format(output))
223 download_urls = asset.get('download_urls')
224 if isinstance(download_urls, dict):
225 video = download_urls.get('Video')
226 if isinstance(video, list):
227 for format_ in video:
228 video_url = format_.get('file')
231 format_id = format_.get('label')
233 'url': format_['file'],
234 'height': int_or_none(format_id),
237 # Some videos contain additional metadata (e.g.
238 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
239 output = outputs.get(format_id)
240 if isinstance(output, dict):
241 output_format = extract_output_format(output)
242 output_format.update(f)
245 f['format_id'] = '%sp' % format_id
248 self._sort_formats(formats)
253 'description': description,
254 'thumbnail': thumbnail,
255 'duration': duration,
260 class UdemyCourseIE(UdemyIE):
261 IE_NAME = 'udemy:course'
262 _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
266 def suitable(cls, url):
267 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
269 def _real_extract(self, url):
270 course_path = self._match_id(url)
272 webpage = self._download_webpage(url, course_path)
274 response = self._download_json(
275 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
276 course_path, 'Downloading course JSON')
278 course_id = response['id']
279 course_title = response.get('title')
281 self._enroll_course(url, webpage, course_id)
283 response = self._download_json(
284 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
285 course_id, 'Downloading course curriculum')
288 chapter, chapter_number = None, None
289 for asset in response:
290 asset_type = asset.get('assetType') or asset.get('asset_type')
291 if asset_type == 'Video':
292 asset_id = asset.get('id')
295 '_type': 'url_transparent',
296 'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
297 'ie_key': UdemyIE.ie_key(),
300 entry['chapter_number'] = chapter_number
302 entry['chapter'] = chapter
303 entries.append(entry)
304 elif asset.get('type') == 'chapter':
305 chapter_number = asset.get('index') or asset.get('object_index')
306 chapter = asset.get('title')
308 return self.playlist_result(entries, course_id, course_title)