]>
Commit | Line | Data |
---|---|---|
e5de3f6c S |
1 | from __future__ import unicode_literals |
2 | ||
e5de3f6c | 3 | from .common import InfoExtractor |
1cc79574 | 4 | from ..compat import ( |
328f82d5 | 5 | compat_HTTPError, |
e5de3f6c S |
6 | compat_urllib_parse, |
7 | compat_urllib_request, | |
1cc79574 PH |
8 | ) |
9 | from ..utils import ( | |
e5de3f6c | 10 | ExtractorError, |
328f82d5 | 11 | float_or_none, |
3b35c342 | 12 | int_or_none, |
5c2266df | 13 | sanitized_Request, |
e5de3f6c S |
14 | ) |
15 | ||
16 | ||
17 | class UdemyIE(InfoExtractor): | |
18 | IE_NAME = 'udemy' | |
19 | _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)' | |
dcd4d95c S |
20 | _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1' |
21 | _ORIGIN_URL = 'https://www.udemy.com' | |
328f82d5 S |
22 | _SUCCESSFULLY_ENROLLED = '>You have enrolled in this course!<' |
23 | _ALREADY_ENROLLED = '>You are already taking this course.<' | |
e5de3f6c S |
24 | _NETRC_MACHINE = 'udemy' |
25 | ||
6563837e | 26 | _TESTS = [{ |
e5de3f6c S |
27 | 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757', |
28 | 'md5': '98eda5b657e752cf945d8445e261b5c5', | |
29 | 'info_dict': { | |
30 | 'id': '160614', | |
31 | 'ext': 'mp4', | |
32 | 'title': 'Introduction and Installation', | |
33 | 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876', | |
34 | 'duration': 579.29, | |
35 | }, | |
36 | 'skip': 'Requires udemy account credentials', | |
6563837e | 37 | }] |
e5de3f6c | 38 | |
328f82d5 S |
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) | |
49 | ||
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({ | |
54 | 'video_only': '', | |
55 | 'auto_play': '', | |
56 | 'fields[lecture]': 'title,description,asset', | |
57 | 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data', | |
58 | 'instructorPreviewMode': 'False', | |
59 | })), | |
24121bc7 | 60 | lecture_id, 'Downloading lecture JSON') |
328f82d5 | 61 | |
e5de3f6c S |
62 | def _handle_error(self, response): |
63 | if not isinstance(response, dict): | |
64 | return | |
65 | error = response.get('error') | |
66 | if error: | |
67 | error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message')) | |
68 | error_data = error.get('data') | |
69 | if error_data: | |
70 | error_str += ' - %s' % error_data.get('formErrors') | |
71 | raise ExtractorError(error_str, expected=True) | |
72 | ||
24121bc7 | 73 | def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'): |
e2937118 S |
74 | headers = { |
75 | 'X-Udemy-Snail-Case': 'true', | |
76 | 'X-Requested-With': 'XMLHttpRequest', | |
77 | } | |
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 | |
328f82d5 | 83 | headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value |
61c0663c S |
84 | |
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) | |
88 | else: | |
5c2266df | 89 | url_or_request = sanitized_Request(url_or_request, headers=headers) |
61c0663c | 90 | |
24121bc7 | 91 | response = super(UdemyIE, self)._download_json(url_or_request, video_id, note) |
61c0663c S |
92 | self._handle_error(response) |
93 | return response | |
e2937118 | 94 | |
e5de3f6c S |
95 | def _real_initialize(self): |
96 | self._login() | |
97 | ||
98 | def _login(self): | |
99 | (username, password) = self._get_login_info() | |
100 | if username is None: | |
78717fc3 | 101 | return |
e5de3f6c S |
102 | |
103 | login_popup = self._download_webpage( | |
dcd4d95c | 104 | self._LOGIN_URL, None, 'Downloading login popup') |
e5de3f6c | 105 | |
d609edf4 S |
106 | def is_logged(webpage): |
107 | return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<']) | |
108 | ||
109 | # already logged in | |
110 | if is_logged(login_popup): | |
e5de3f6c S |
111 | return |
112 | ||
dcd4d95c | 113 | login_form = self._form_hidden_inputs('login-form', login_popup) |
e5de3f6c | 114 | |
dcd4d95c | 115 | login_form.update({ |
dcd4d95c S |
116 | 'email': username.encode('utf-8'), |
117 | 'password': password.encode('utf-8'), | |
118 | }) | |
119 | ||
5c2266df | 120 | request = sanitized_Request( |
61c0663c | 121 | self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8')) |
dcd4d95c S |
122 | request.add_header('Referer', self._ORIGIN_URL) |
123 | request.add_header('Origin', self._ORIGIN_URL) | |
124 | ||
125 | response = self._download_webpage( | |
e2937118 | 126 | request, None, 'Logging in as %s' % username) |
e5de3f6c | 127 | |
d609edf4 | 128 | if not is_logged(response): |
dcd4d95c S |
129 | error = self._html_search_regex( |
130 | r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>', | |
131 | response, 'error message', default=None) | |
132 | if error: | |
133 | raise ExtractorError('Unable to login: %s' % error, expected=True) | |
e5de3f6c S |
134 | raise ExtractorError('Unable to log in') |
135 | ||
136 | def _real_extract(self, url): | |
810fb84d | 137 | lecture_id = self._match_id(url) |
e5de3f6c | 138 | |
328f82d5 S |
139 | webpage = self._download_webpage(url, lecture_id) |
140 | ||
141 | course_id = self._search_regex( | |
142 | r'data-course-id=["\'](\d+)', webpage, 'course id') | |
e5de3f6c | 143 | |
328f82d5 S |
144 | try: |
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) | |
151 | else: | |
152 | raise | |
153 | ||
154 | title = lecture['title'] | |
155 | description = lecture.get('description') | |
156 | ||
157 | asset = lecture['asset'] | |
158 | ||
159 | asset_type = asset.get('assetType') or asset.get('asset_type') | |
e2937118 S |
160 | if asset_type != 'Video': |
161 | raise ExtractorError( | |
162 | 'Lecture %s is not a video' % lecture_id, expected=True) | |
e5de3f6c | 163 | |
e2937118 | 164 | stream_url = asset.get('streamUrl') or asset.get('stream_url') |
328f82d5 S |
165 | if stream_url: |
166 | youtube_url = self._search_regex( | |
167 | r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None) | |
168 | if youtube_url: | |
169 | return self.url_result(youtube_url, 'Youtube') | |
e5de3f6c S |
170 | |
171 | video_id = asset['id'] | |
e2937118 | 172 | thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url') |
328f82d5 S |
173 | duration = float_or_none(asset.get('data', {}).get('duration')) |
174 | outputs = asset.get('data', {}).get('outputs', {}) | |
175 | ||
176 | formats = [] | |
177 | for format_ in asset.get('download_urls', {}).get('Video', []): | |
178 | video_url = format_.get('file') | |
179 | if not video_url: | |
180 | continue | |
181 | format_id = format_.get('label') | |
182 | f = { | |
183 | 'url': format_['file'], | |
184 | 'height': int_or_none(format_id), | |
185 | } | |
186 | if 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): | |
191 | f.update({ | |
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')), | |
3b35c342 | 203 | }) |
328f82d5 S |
204 | else: |
205 | f['format_id'] = '%sp' % format_id | |
206 | formats.append(f) | |
3b35c342 S |
207 | |
208 | self._sort_formats(formats) | |
e5de3f6c | 209 | |
e5de3f6c S |
210 | return { |
211 | 'id': video_id, | |
212 | 'title': title, | |
213 | 'description': description, | |
214 | 'thumbnail': thumbnail, | |
215 | 'duration': duration, | |
216 | 'formats': formats | |
217 | } | |
218 | ||
219 | ||
220 | class UdemyCourseIE(UdemyIE): | |
221 | IE_NAME = 'udemy:course' | |
328f82d5 | 222 | _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)' |
6563837e | 223 | _TESTS = [] |
e5de3f6c S |
224 | |
225 | @classmethod | |
226 | def suitable(cls, url): | |
227 | return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url) | |
228 | ||
229 | def _real_extract(self, url): | |
328f82d5 S |
230 | course_path = self._match_id(url) |
231 | ||
232 | webpage = self._download_webpage(url, course_path) | |
e5de3f6c | 233 | |
61c0663c | 234 | response = self._download_json( |
e2937118 S |
235 | 'https://www.udemy.com/api-1.1/courses/%s' % course_path, |
236 | course_path, 'Downloading course JSON') | |
e5de3f6c | 237 | |
328f82d5 S |
238 | course_id = response['id'] |
239 | course_title = response.get('title') | |
e5de3f6c | 240 | |
328f82d5 | 241 | self._enroll_course(webpage, course_id) |
e5de3f6c | 242 | |
61c0663c | 243 | response = self._download_json( |
e2937118 S |
244 | 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id, |
245 | course_id, 'Downloading course curriculum') | |
e5de3f6c S |
246 | |
247 | entries = [ | |
e2937118 S |
248 | self.url_result( |
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' | |
e5de3f6c S |
251 | ] |
252 | ||
5f6a1245 | 253 | return self.playlist_result(entries, course_id, course_title) |