1 from __future__ import unicode_literals
3 from .common import InfoExtractor
6 compat_urllib_parse_urlencode,
20 class UdemyIE(InfoExtractor):
27 lecture/view/?\?lectureId=|
28 [^/]+/learn/v4/t/lecture/
32 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
33 _ORIGIN_URL = 'https://www.udemy.com'
34 _NETRC_MACHINE = 'udemy'
37 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
38 'md5': '98eda5b657e752cf945d8445e261b5c5',
42 'title': 'Introduction and Installation',
43 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
46 'skip': 'Requires udemy account credentials',
49 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
50 'only_matching': True,
53 def _enroll_course(self, base_url, webpage, course_id):
54 checkout_url = unescapeHTML(self._search_regex(
55 r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/payment/checkout/.+?)\1',
56 webpage, 'checkout url', group='url', default=None))
59 'Course %s is not free. You have to pay for it before you can download. '
60 'Use this URL to confirm purchase: %s' % (course_id, checkout_url), expected=True)
62 enroll_url = unescapeHTML(self._search_regex(
63 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
64 webpage, 'enroll url', group='url', default=None))
66 if not enroll_url.startswith('http'):
67 enroll_url = compat_urlparse.urljoin(base_url, enroll_url)
68 webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course')
69 if '>You have enrolled in' in webpage:
70 self.to_screen('%s: Successfully enrolled in the course' % course_id)
72 def _download_lecture(self, course_id, lecture_id):
73 return self._download_json(
74 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
75 course_id, lecture_id, compat_urllib_parse_urlencode({
78 'fields[lecture]': 'title,description,asset',
79 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
80 'instructorPreviewMode': 'False',
82 lecture_id, 'Downloading lecture JSON')
84 def _handle_error(self, response):
85 if not isinstance(response, dict):
87 error = response.get('error')
89 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
90 error_data = error.get('data')
92 error_str += ' - %s' % error_data.get('formErrors')
93 raise ExtractorError(error_str, expected=True)
95 def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
97 'X-Udemy-Snail-Case': 'true',
98 'X-Requested-With': 'XMLHttpRequest',
100 for cookie in self._downloader.cookiejar:
101 if cookie.name == 'client_id':
102 headers['X-Udemy-Client-Id'] = cookie.value
103 elif cookie.name == 'access_token':
104 headers['X-Udemy-Bearer-Token'] = cookie.value
105 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
107 if isinstance(url_or_request, compat_urllib_request.Request):
108 for header, value in headers.items():
109 url_or_request.add_header(header, value)
111 url_or_request = sanitized_Request(url_or_request, headers=headers)
113 response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
114 self._handle_error(response)
117 def _real_initialize(self):
121 (username, password) = self._get_login_info()
125 login_popup = self._download_webpage(
126 self._LOGIN_URL, None, 'Downloading login popup')
128 def is_logged(webpage):
129 return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
132 if is_logged(login_popup):
135 login_form = self._form_hidden_inputs('login-form', login_popup)
138 'email': username.encode('utf-8'),
139 'password': password.encode('utf-8'),
142 request = sanitized_Request(
143 self._LOGIN_URL, urlencode_postdata(login_form))
144 request.add_header('Referer', self._ORIGIN_URL)
145 request.add_header('Origin', self._ORIGIN_URL)
147 response = self._download_webpage(
148 request, None, 'Logging in as %s' % username)
150 if not is_logged(response):
151 error = self._html_search_regex(
152 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
153 response, 'error message', default=None)
155 raise ExtractorError('Unable to login: %s' % error, expected=True)
156 raise ExtractorError('Unable to log in')
158 def _real_extract(self, url):
159 lecture_id = self._match_id(url)
161 webpage = self._download_webpage(url, lecture_id)
163 course_id = self._search_regex(
164 (r'data-course-id=["\'](\d+)', r'"id"\s*:\s*(\d+)'),
165 webpage, 'course id')
168 lecture = self._download_lecture(course_id, lecture_id)
169 except ExtractorError as e:
170 # Error could possibly mean we are not enrolled in the course
171 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
172 self._enroll_course(url, webpage, course_id)
173 lecture = self._download_lecture(course_id, lecture_id)
177 title = lecture['title']
178 description = lecture.get('description')
180 asset = lecture['asset']
182 asset_type = asset.get('assetType') or asset.get('asset_type')
183 if asset_type != 'Video':
184 raise ExtractorError(
185 'Lecture %s is not a video' % lecture_id, expected=True)
187 stream_url = asset.get('streamUrl') or asset.get('stream_url')
189 youtube_url = self._search_regex(
190 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
192 return self.url_result(youtube_url, 'Youtube')
194 video_id = asset['id']
195 thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
196 duration = float_or_none(asset.get('data', {}).get('duration'))
200 def extract_output_format(src):
203 'format_id': '%sp' % (src.get('label') or format_id),
204 'width': int_or_none(src.get('width')),
205 'height': int_or_none(src.get('height')),
206 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
207 'vcodec': src.get('video_codec'),
208 'fps': int_or_none(src.get('frame_rate')),
209 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
210 'acodec': src.get('audio_codec'),
211 'asr': int_or_none(src.get('audio_sample_rate')),
212 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
213 'filesize': int_or_none(src.get('file_size_in_bytes')),
216 outputs = asset.get('data', {}).get('outputs')
217 if not isinstance(outputs, dict):
220 for format_id, output in outputs.items():
221 if isinstance(output, dict) and output.get('url'):
222 formats.append(extract_output_format(output))
224 download_urls = asset.get('download_urls')
225 if isinstance(download_urls, dict):
226 video = download_urls.get('Video')
227 if isinstance(video, list):
228 for format_ in video:
229 video_url = format_.get('file')
232 format_id = format_.get('label')
234 'url': format_['file'],
235 'height': int_or_none(format_id),
238 # Some videos contain additional metadata (e.g.
239 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
240 output = outputs.get(format_id)
241 if isinstance(output, dict):
242 output_format = extract_output_format(output)
243 output_format.update(f)
246 f['format_id'] = '%sp' % format_id
249 self._sort_formats(formats)
254 'description': description,
255 'thumbnail': thumbnail,
256 'duration': duration,
261 class UdemyCourseIE(UdemyIE):
262 IE_NAME = 'udemy:course'
263 _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
267 def suitable(cls, url):
268 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
270 def _real_extract(self, url):
271 course_path = self._match_id(url)
273 webpage = self._download_webpage(url, course_path)
275 response = self._download_json(
276 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
277 course_path, 'Downloading course JSON')
279 course_id = response['id']
280 course_title = response.get('title')
282 self._enroll_course(url, webpage, course_id)
284 response = self._download_json(
285 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
286 course_id, 'Downloading course curriculum')
289 chapter, chapter_number = None, None
290 for asset in response:
291 asset_type = asset.get('assetType') or asset.get('asset_type')
292 if asset_type == 'Video':
293 asset_id = asset.get('id')
296 '_type': 'url_transparent',
297 'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
298 'ie_key': UdemyIE.ie_key(),
301 entry['chapter_number'] = chapter_number
303 entry['chapter'] = chapter
304 entries.append(entry)
305 elif asset.get('type') == 'chapter':
306 chapter_number = asset.get('index') or asset.get('object_index')
307 chapter = asset.get('title')
309 return self.playlist_result(entries, course_id, course_title)