]>
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, | |
ff9d5d09 | 8 | compat_urlparse, |
1cc79574 PH |
9 | ) |
10 | from ..utils import ( | |
e5de3f6c | 11 | ExtractorError, |
328f82d5 | 12 | float_or_none, |
3b35c342 | 13 | int_or_none, |
5c2266df | 14 | sanitized_Request, |
17b2d7ca | 15 | unescapeHTML, |
e5de3f6c S |
16 | ) |
17 | ||
18 | ||
19 | class UdemyIE(InfoExtractor): | |
20 | IE_NAME = 'udemy' | |
21 | _VALID_URL = r'https?://www\.udemy\.com/(?:[^#]+#/lecture/|lecture/view/?\?lectureId=)(?P<id>\d+)' | |
dcd4d95c S |
22 | _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1' |
23 | _ORIGIN_URL = 'https://www.udemy.com' | |
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 | |
ff9d5d09 | 39 | def _enroll_course(self, base_url, webpage, course_id): |
17b2d7ca S |
40 | checkout_url = unescapeHTML(self._search_regex( |
41 | r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/payment/checkout/.+?)\1', | |
42 | webpage, 'checkout url', group='url', default=None)) | |
43 | if checkout_url: | |
44 | raise ExtractorError( | |
f20756fb | 45 | 'Course %s is not free. You have to pay for it before you can download. ' |
17b2d7ca S |
46 | 'Use this URL to confirm purchase: %s' % (course_id, checkout_url), expected=True) |
47 | ||
48 | enroll_url = unescapeHTML(self._search_regex( | |
ff9d5d09 | 49 | r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1', |
17b2d7ca S |
50 | webpage, 'enroll url', group='url', default=None)) |
51 | if enroll_url: | |
ff9d5d09 S |
52 | if not enroll_url.startswith('http'): |
53 | enroll_url = compat_urlparse.urljoin(base_url, enroll_url) | |
17b2d7ca S |
54 | webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course') |
55 | if '>You have enrolled in' in webpage: | |
56 | self.to_screen('%s: Successfully enrolled in the course' % course_id) | |
328f82d5 S |
57 | |
58 | def _download_lecture(self, course_id, lecture_id): | |
59 | return self._download_json( | |
60 | 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % ( | |
61 | course_id, lecture_id, compat_urllib_parse.urlencode({ | |
62 | 'video_only': '', | |
63 | 'auto_play': '', | |
64 | 'fields[lecture]': 'title,description,asset', | |
65 | 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data', | |
66 | 'instructorPreviewMode': 'False', | |
67 | })), | |
24121bc7 | 68 | lecture_id, 'Downloading lecture JSON') |
328f82d5 | 69 | |
e5de3f6c S |
70 | def _handle_error(self, response): |
71 | if not isinstance(response, dict): | |
72 | return | |
73 | error = response.get('error') | |
74 | if error: | |
75 | error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message')) | |
76 | error_data = error.get('data') | |
77 | if error_data: | |
78 | error_str += ' - %s' % error_data.get('formErrors') | |
79 | raise ExtractorError(error_str, expected=True) | |
80 | ||
24121bc7 | 81 | def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'): |
e2937118 S |
82 | headers = { |
83 | 'X-Udemy-Snail-Case': 'true', | |
84 | 'X-Requested-With': 'XMLHttpRequest', | |
85 | } | |
86 | for cookie in self._downloader.cookiejar: | |
87 | if cookie.name == 'client_id': | |
88 | headers['X-Udemy-Client-Id'] = cookie.value | |
89 | elif cookie.name == 'access_token': | |
90 | headers['X-Udemy-Bearer-Token'] = cookie.value | |
328f82d5 | 91 | headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value |
61c0663c S |
92 | |
93 | if isinstance(url_or_request, compat_urllib_request.Request): | |
94 | for header, value in headers.items(): | |
95 | url_or_request.add_header(header, value) | |
96 | else: | |
5c2266df | 97 | url_or_request = sanitized_Request(url_or_request, headers=headers) |
61c0663c | 98 | |
24121bc7 | 99 | response = super(UdemyIE, self)._download_json(url_or_request, video_id, note) |
61c0663c S |
100 | self._handle_error(response) |
101 | return response | |
e2937118 | 102 | |
e5de3f6c S |
103 | def _real_initialize(self): |
104 | self._login() | |
105 | ||
106 | def _login(self): | |
107 | (username, password) = self._get_login_info() | |
108 | if username is None: | |
78717fc3 | 109 | return |
e5de3f6c S |
110 | |
111 | login_popup = self._download_webpage( | |
dcd4d95c | 112 | self._LOGIN_URL, None, 'Downloading login popup') |
e5de3f6c | 113 | |
d609edf4 S |
114 | def is_logged(webpage): |
115 | return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<']) | |
116 | ||
117 | # already logged in | |
118 | if is_logged(login_popup): | |
e5de3f6c S |
119 | return |
120 | ||
dcd4d95c | 121 | login_form = self._form_hidden_inputs('login-form', login_popup) |
e5de3f6c | 122 | |
dcd4d95c | 123 | login_form.update({ |
dcd4d95c S |
124 | 'email': username.encode('utf-8'), |
125 | 'password': password.encode('utf-8'), | |
126 | }) | |
127 | ||
5c2266df | 128 | request = sanitized_Request( |
61c0663c | 129 | self._LOGIN_URL, compat_urllib_parse.urlencode(login_form).encode('utf-8')) |
dcd4d95c S |
130 | request.add_header('Referer', self._ORIGIN_URL) |
131 | request.add_header('Origin', self._ORIGIN_URL) | |
132 | ||
133 | response = self._download_webpage( | |
e2937118 | 134 | request, None, 'Logging in as %s' % username) |
e5de3f6c | 135 | |
d609edf4 | 136 | if not is_logged(response): |
dcd4d95c S |
137 | error = self._html_search_regex( |
138 | r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>', | |
139 | response, 'error message', default=None) | |
140 | if error: | |
141 | raise ExtractorError('Unable to login: %s' % error, expected=True) | |
e5de3f6c S |
142 | raise ExtractorError('Unable to log in') |
143 | ||
144 | def _real_extract(self, url): | |
810fb84d | 145 | lecture_id = self._match_id(url) |
e5de3f6c | 146 | |
328f82d5 S |
147 | webpage = self._download_webpage(url, lecture_id) |
148 | ||
149 | course_id = self._search_regex( | |
70cab344 | 150 | (r'data-course-id=["\'](\d+)', r'"id"\s*:\s*(\d+)'), |
a7ba57dc | 151 | webpage, 'course id') |
e5de3f6c | 152 | |
328f82d5 S |
153 | try: |
154 | lecture = self._download_lecture(course_id, lecture_id) | |
155 | except ExtractorError as e: | |
156 | # Error could possibly mean we are not enrolled in the course | |
157 | if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403: | |
ff9d5d09 | 158 | self._enroll_course(url, webpage, course_id) |
3092fc40 | 159 | lecture = self._download_lecture(course_id, lecture_id) |
328f82d5 S |
160 | else: |
161 | raise | |
162 | ||
163 | title = lecture['title'] | |
164 | description = lecture.get('description') | |
165 | ||
166 | asset = lecture['asset'] | |
167 | ||
168 | asset_type = asset.get('assetType') or asset.get('asset_type') | |
e2937118 S |
169 | if asset_type != 'Video': |
170 | raise ExtractorError( | |
171 | 'Lecture %s is not a video' % lecture_id, expected=True) | |
e5de3f6c | 172 | |
e2937118 | 173 | stream_url = asset.get('streamUrl') or asset.get('stream_url') |
328f82d5 S |
174 | if stream_url: |
175 | youtube_url = self._search_regex( | |
176 | r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None) | |
177 | if youtube_url: | |
178 | return self.url_result(youtube_url, 'Youtube') | |
e5de3f6c S |
179 | |
180 | video_id = asset['id'] | |
e2937118 | 181 | thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url') |
328f82d5 S |
182 | duration = float_or_none(asset.get('data', {}).get('duration')) |
183 | outputs = asset.get('data', {}).get('outputs', {}) | |
184 | ||
185 | formats = [] | |
186 | for format_ in asset.get('download_urls', {}).get('Video', []): | |
187 | video_url = format_.get('file') | |
188 | if not video_url: | |
189 | continue | |
190 | format_id = format_.get('label') | |
191 | f = { | |
192 | 'url': format_['file'], | |
193 | 'height': int_or_none(format_id), | |
194 | } | |
195 | if format_id: | |
196 | # Some videos contain additional metadata (e.g. | |
197 | # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208) | |
198 | output = outputs.get(format_id) | |
199 | if isinstance(output, dict): | |
200 | f.update({ | |
201 | 'format_id': '%sp' % (output.get('label') or format_id), | |
202 | 'width': int_or_none(output.get('width')), | |
203 | 'height': int_or_none(output.get('height')), | |
204 | 'vbr': int_or_none(output.get('video_bitrate_in_kbps')), | |
205 | 'vcodec': output.get('video_codec'), | |
206 | 'fps': int_or_none(output.get('frame_rate')), | |
207 | 'abr': int_or_none(output.get('audio_bitrate_in_kbps')), | |
208 | 'acodec': output.get('audio_codec'), | |
209 | 'asr': int_or_none(output.get('audio_sample_rate')), | |
210 | 'tbr': int_or_none(output.get('total_bitrate_in_kbps')), | |
211 | 'filesize': int_or_none(output.get('file_size_in_bytes')), | |
3b35c342 | 212 | }) |
328f82d5 S |
213 | else: |
214 | f['format_id'] = '%sp' % format_id | |
215 | formats.append(f) | |
3b35c342 S |
216 | |
217 | self._sort_formats(formats) | |
e5de3f6c | 218 | |
e5de3f6c S |
219 | return { |
220 | 'id': video_id, | |
221 | 'title': title, | |
222 | 'description': description, | |
223 | 'thumbnail': thumbnail, | |
224 | 'duration': duration, | |
225 | 'formats': formats | |
226 | } | |
227 | ||
228 | ||
229 | class UdemyCourseIE(UdemyIE): | |
230 | IE_NAME = 'udemy:course' | |
328f82d5 | 231 | _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)' |
6563837e | 232 | _TESTS = [] |
e5de3f6c S |
233 | |
234 | @classmethod | |
235 | def suitable(cls, url): | |
236 | return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url) | |
237 | ||
238 | def _real_extract(self, url): | |
328f82d5 S |
239 | course_path = self._match_id(url) |
240 | ||
241 | webpage = self._download_webpage(url, course_path) | |
e5de3f6c | 242 | |
61c0663c | 243 | response = self._download_json( |
e2937118 S |
244 | 'https://www.udemy.com/api-1.1/courses/%s' % course_path, |
245 | course_path, 'Downloading course JSON') | |
e5de3f6c | 246 | |
328f82d5 S |
247 | course_id = response['id'] |
248 | course_title = response.get('title') | |
e5de3f6c | 249 | |
ff9d5d09 | 250 | self._enroll_course(url, webpage, course_id) |
e5de3f6c | 251 | |
61c0663c | 252 | response = self._download_json( |
e2937118 S |
253 | 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id, |
254 | course_id, 'Downloading course curriculum') | |
e5de3f6c | 255 | |
4d402db5 | 256 | entries = [] |
5bafcf65 | 257 | chapter, chapter_number = None, None |
4d402db5 S |
258 | for asset in response: |
259 | asset_type = asset.get('assetType') or asset.get('asset_type') | |
260 | if asset_type == 'Video': | |
261 | asset_id = asset.get('id') | |
262 | if asset_id: | |
263 | entry = { | |
264 | '_type': 'url_transparent', | |
265 | 'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), | |
266 | 'ie_key': UdemyIE.ie_key(), | |
267 | } | |
5bafcf65 S |
268 | if chapter_number: |
269 | entry['chapter_number'] = chapter_number | |
4d402db5 S |
270 | if chapter: |
271 | entry['chapter'] = chapter | |
272 | entries.append(entry) | |
273 | elif asset.get('type') == 'chapter': | |
5bafcf65 | 274 | chapter_number = asset.get('index') or asset.get('object_index') |
4d402db5 | 275 | chapter = asset.get('title') |
e5de3f6c | 276 | |
5f6a1245 | 277 | return self.playlist_result(entries, course_id, course_title) |