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 def combine_url(base_url, url):
59 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
61 checkout_url = unescapeHTML(self._search_regex(
62 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/payment/checkout/.+?)\1',
63 webpage, 'checkout url', group='url', default=None))
66 'Course %s is not free. You have to pay for it before you can download. '
67 'Use this URL to confirm purchase: %s'
68 % (course_id, combine_url(base_url, checkout_url)),
71 enroll_url = unescapeHTML(self._search_regex(
72 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
73 webpage, 'enroll url', group='url', default=None))
75 webpage = self._download_webpage(
76 combine_url(base_url, enroll_url),
77 course_id, 'Enrolling in the course')
78 if '>You have enrolled in' in webpage:
79 self.to_screen('%s: Successfully enrolled in the course' % course_id)
81 def _download_lecture(self, course_id, lecture_id):
82 return self._download_json(
83 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % (
84 course_id, lecture_id, compat_urllib_parse_urlencode({
85 'fields[lecture]': 'title,description,view_html,asset',
86 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data',
88 lecture_id, 'Downloading lecture JSON')
90 def _handle_error(self, response):
91 if not isinstance(response, dict):
93 error = response.get('error')
95 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
96 error_data = error.get('data')
98 error_str += ' - %s' % error_data.get('formErrors')
99 raise ExtractorError(error_str, expected=True)
101 def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
103 'X-Udemy-Snail-Case': 'true',
104 'X-Requested-With': 'XMLHttpRequest',
106 for cookie in self._downloader.cookiejar:
107 if cookie.name == 'client_id':
108 headers['X-Udemy-Client-Id'] = cookie.value
109 elif cookie.name == 'access_token':
110 headers['X-Udemy-Bearer-Token'] = cookie.value
111 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
113 if isinstance(url_or_request, compat_urllib_request.Request):
114 for header, value in headers.items():
115 url_or_request.add_header(header, value)
117 url_or_request = sanitized_Request(url_or_request, headers=headers)
119 response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
120 self._handle_error(response)
123 def _real_initialize(self):
127 (username, password) = self._get_login_info()
131 login_popup = self._download_webpage(
132 self._LOGIN_URL, None, 'Downloading login popup')
134 def is_logged(webpage):
135 return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
138 if is_logged(login_popup):
141 login_form = self._form_hidden_inputs('login-form', login_popup)
144 'email': username.encode('utf-8'),
145 'password': password.encode('utf-8'),
148 request = sanitized_Request(
149 self._LOGIN_URL, urlencode_postdata(login_form))
150 request.add_header('Referer', self._ORIGIN_URL)
151 request.add_header('Origin', self._ORIGIN_URL)
153 response = self._download_webpage(
154 request, None, 'Logging in as %s' % username)
156 if not is_logged(response):
157 error = self._html_search_regex(
158 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
159 response, 'error message', default=None)
161 raise ExtractorError('Unable to login: %s' % error, expected=True)
162 raise ExtractorError('Unable to log in')
164 def _real_extract(self, url):
165 lecture_id = self._match_id(url)
167 webpage = self._download_webpage(url, lecture_id)
169 course_id = self._search_regex(
170 (r'data-course-id=["\'](\d+)', r'"id"\s*:\s*(\d+)'),
171 webpage, 'course id')
174 lecture = self._download_lecture(course_id, lecture_id)
175 except ExtractorError as e:
176 # Error could possibly mean we are not enrolled in the course
177 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
178 self._enroll_course(url, webpage, course_id)
179 lecture = self._download_lecture(course_id, lecture_id)
183 title = lecture['title']
184 description = lecture.get('description')
186 asset = lecture['asset']
188 asset_type = asset.get('assetType') or asset.get('asset_type')
189 if asset_type != 'Video':
190 raise ExtractorError(
191 'Lecture %s is not a video' % lecture_id, expected=True)
193 stream_url = asset.get('streamUrl') or asset.get('stream_url')
195 youtube_url = self._search_regex(
196 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
198 return self.url_result(youtube_url, 'Youtube')
200 video_id = asset['id']
201 thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
202 duration = float_or_none(asset.get('data', {}).get('duration'))
206 def extract_output_format(src):
209 'format_id': '%sp' % (src.get('height') or format_id),
210 'width': int_or_none(src.get('width')),
211 'height': int_or_none(src.get('height')),
212 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
213 'vcodec': src.get('video_codec'),
214 'fps': int_or_none(src.get('frame_rate')),
215 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
216 'acodec': src.get('audio_codec'),
217 'asr': int_or_none(src.get('audio_sample_rate')),
218 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
219 'filesize': int_or_none(src.get('file_size_in_bytes')),
222 outputs = asset.get('data', {}).get('outputs')
223 if not isinstance(outputs, dict):
226 def add_output_format_meta(f, key):
227 output = outputs.get(key)
228 if isinstance(output, dict):
229 output_format = extract_output_format(output)
230 output_format.update(f)
234 download_urls = asset.get('download_urls')
235 if isinstance(download_urls, dict):
236 video = download_urls.get('Video')
237 if isinstance(video, list):
238 for format_ in video:
239 video_url = format_.get('file')
242 format_id = format_.get('label')
244 'url': format_['file'],
245 'format_id': '%sp' % format_id,
246 'height': int_or_none(format_id),
249 # Some videos contain additional metadata (e.g.
250 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
251 f = add_output_format_meta(f, format_id)
254 view_html = lecture.get('view_html')
256 view_html_urls = set()
257 for source in re.findall(r'<source[^>]+>', view_html):
258 attributes = extract_attributes(source)
259 src = attributes.get('src')
262 res = attributes.get('data-res')
263 height = int_or_none(res)
264 if src in view_html_urls:
266 view_html_urls.add(src)
267 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
268 m3u8_formats = self._extract_m3u8_formats(
269 src, video_id, 'mp4', entry_protocol='m3u8_native',
270 m3u8_id='hls', fatal=False)
271 for f in m3u8_formats:
272 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
274 if not f.get('height'):
275 f['height'] = int(m.group('height'))
277 f['tbr'] = int(m.group('tbr'))
278 formats.extend(m3u8_formats)
280 formats.append(add_output_format_meta({
282 'format_id': '%dp' % height if height else None,
286 self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
291 'description': description,
292 'thumbnail': thumbnail,
293 'duration': duration,
298 class UdemyCourseIE(UdemyIE):
299 IE_NAME = 'udemy:course'
300 _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)'
304 def suitable(cls, url):
305 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
307 def _real_extract(self, url):
308 course_path = self._match_id(url)
310 webpage = self._download_webpage(url, course_path)
312 response = self._download_json(
313 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
314 course_path, 'Downloading course JSON')
316 course_id = response['id']
317 course_title = response.get('title')
319 self._enroll_course(url, webpage, course_id)
321 response = self._download_json(
322 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
323 course_id, 'Downloading course curriculum')
326 chapter, chapter_number = None, None
327 for asset in response:
328 asset_type = asset.get('assetType') or asset.get('asset_type')
329 if asset_type == 'Video':
330 asset_id = asset.get('id')
333 '_type': 'url_transparent',
334 'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']),
335 'ie_key': UdemyIE.ie_key(),
338 entry['chapter_number'] = chapter_number
340 entry['chapter'] = chapter
341 entries.append(entry)
342 elif asset.get('type') == 'chapter':
343 chapter_number = asset.get('index') or asset.get('object_index')
344 chapter = asset.get('title')
346 return self.playlist_result(entries, course_id, course_title)