1 from __future__ import unicode_literals
5 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 _NETRC_MACHINE = 'udemy'
25 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
26 'md5': '98eda5b657e752cf945d8445e261b5c5',
30 'title': 'Introduction and Installation',
31 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
34 'skip': 'Requires udemy account credentials',
37 def _handle_error(self, response):
38 if not isinstance(response, dict):
40 error = response.get('error')
42 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
43 error_data = error.get('data')
45 error_str += ' - %s' % error_data.get('formErrors')
46 raise ExtractorError(error_str, expected=True)
48 def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'):
50 'X-Udemy-Snail-Case': 'true',
51 'X-Requested-With': 'XMLHttpRequest',
53 for cookie in self._downloader.cookiejar:
54 if cookie.name == 'client_id':
55 headers['X-Udemy-Client-Id'] = cookie.value
56 elif cookie.name == 'access_token':
57 headers['X-Udemy-Bearer-Token'] = cookie.value
59 if isinstance(url_or_request, compat_urllib_request.Request):
60 for header, value in headers.items():
61 url_or_request.add_header(header, value)
63 url_or_request = sanitized_Request(url_or_request, headers=headers)
65 response = super(UdemyIE, self)._download_json(url_or_request, video_id, note)
66 self._handle_error(response)
69 def _real_initialize(self):
73 (username, password) = self._get_login_info()
75 self.raise_login_required('Udemy account is required')
77 login_popup = self._download_webpage(
78 self._LOGIN_URL, None, 'Downloading login popup')
80 def is_logged(webpage):
81 return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<'])
84 if is_logged(login_popup):
87 login_form = self._form_hidden_inputs('login-form', login_popup)
90 'email': username.encode('utf-8'),
91 'password': password.encode('utf-8'),
94 request = sanitized_Request(
95 self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
96 request.add_header('Referer', self._ORIGIN_URL)
97 request.add_header('Origin', self._ORIGIN_URL)
99 response = self._download_webpage(
100 request, None, 'Logging in as %s' % username)
102 if not is_logged(response):
103 error = self._html_search_regex(
104 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
105 response, 'error message', default=None)
107 raise ExtractorError('Unable to login: %s' % error, expected=True)
108 raise ExtractorError('Unable to log in')
110 def _real_extract(self, url):
111 lecture_id = self._match_id(url)
113 lecture = self._download_json(
114 'https://www.udemy.com/api-1.1/lectures/%s' % lecture_id,
115 lecture_id, 'Downloading lecture JSON')
117 asset_type = lecture.get('assetType') or lecture.get('asset_type')
118 if asset_type != 'Video':
119 raise ExtractorError(
120 'Lecture %s is not a video' % lecture_id, expected=True)
122 asset = lecture['asset']
124 stream_url = asset.get('streamUrl') or asset.get('stream_url')
125 mobj = re.search(r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url)
127 return self.url_result(mobj.group(1), 'Youtube')
129 video_id = asset['id']
130 thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url')
131 duration = int_or_none(asset.get('data', {}).get('duration'))
133 download_url = asset.get('downloadUrl') or asset.get('download_url')
135 video = download_url.get('Video') or download_url.get('video')
136 video_480p = download_url.get('Video480p') or download_url.get('video_480p')
139 'url': video_480p[0],
140 'format_id': 'download-360p',
143 'format_id': 'download-720p',
146 # Some videos also contain formats in asset['data']['outputs'] (e.g.
147 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
148 outputs = asset.get('data', {}).get('outputs')
149 if isinstance(outputs, dict):
150 for format_id, f in outputs.items():
151 video_url = f.get('url')
155 'format_id': '%sp' % (f.get('labe1l') or format_id),
156 'width': int_or_none(f.get('width')),
157 'height': int_or_none(f.get('height')),
158 'vbr': int_or_none(f.get('video_bitrate_in_kbps')),
159 'vcodec': f.get('video_codec'),
160 'fps': int_or_none(f.get('frame_rate')),
161 'abr': int_or_none(f.get('audio_bitrate_in_kbps')),
162 'acodec': f.get('audio_codec'),
163 'asr': int_or_none(f.get('audio_sample_rate')),
164 'tbr': int_or_none(f.get('total_bitrate_in_kbps')),
165 'filesize': int_or_none(f.get('file_size_in_bytes')),
168 self._sort_formats(formats)
170 title = lecture['title']
171 description = lecture.get('description')
176 'description': description,
177 'thumbnail': thumbnail,
178 'duration': duration,
183 class UdemyCourseIE(UdemyIE):
184 IE_NAME = 'udemy:course'
185 _VALID_URL = r'https?://www\.udemy\.com/(?P<coursepath>[\da-z-]+)'
186 _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<'
187 _ALREADY_ENROLLED = '>You are already taking this course.<'
191 def suitable(cls, url):
192 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
194 def _real_extract(self, url):
195 mobj = re.match(self._VALID_URL, url)
196 course_path = mobj.group('coursepath')
198 response = self._download_json(
199 'https://www.udemy.com/api-1.1/courses/%s' % course_path,
200 course_path, 'Downloading course JSON')
202 course_id = int(response['id'])
203 course_title = response['title']
205 webpage = self._download_webpage(
206 'https://www.udemy.com/course/subscribe/?courseId=%s' % course_id,
207 course_id, 'Enrolling in the course')
209 if self._SUCCESSFULLY_ENROLLED in webpage:
210 self.to_screen('%s: Successfully enrolled in' % course_id)
211 elif self._ALREADY_ENROLLED in webpage:
212 self.to_screen('%s: Already enrolled in' % course_id)
214 response = self._download_json(
215 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id,
216 course_id, 'Downloading course curriculum')
220 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), 'Udemy')
221 for asset in response if asset.get('assetType') or asset.get('asset_type') == 'Video'
224 return self.playlist_result(entries, course_id, course_title)