]>
Commit | Line | Data |
---|---|---|
e5de3f6c S |
1 | from __future__ import unicode_literals |
2 | ||
efcba804 S |
3 | import re |
4 | ||
e5de3f6c | 5 | from .common import InfoExtractor |
1cc79574 | 6 | from ..compat import ( |
328f82d5 | 7 | compat_HTTPError, |
15707c7e | 8 | compat_urllib_parse_urlencode, |
e5de3f6c | 9 | compat_urllib_request, |
ff9d5d09 | 10 | compat_urlparse, |
1cc79574 PH |
11 | ) |
12 | from ..utils import ( | |
efcba804 S |
13 | determine_ext, |
14 | extract_attributes, | |
e5de3f6c | 15 | ExtractorError, |
328f82d5 | 16 | float_or_none, |
3b35c342 | 17 | int_or_none, |
5c2266df | 18 | sanitized_Request, |
17b2d7ca | 19 | unescapeHTML, |
6e6bc8da | 20 | urlencode_postdata, |
e5de3f6c S |
21 | ) |
22 | ||
23 | ||
24 | class UdemyIE(InfoExtractor): | |
25 | IE_NAME = 'udemy' | |
5eb7db4e S |
26 | _VALID_URL = r'''(?x) |
27 | https?:// | |
28 | www\.udemy\.com/ | |
29 | (?: | |
30 | [^#]+\#/lecture/| | |
31 | lecture/view/?\?lectureId=| | |
32 | [^/]+/learn/v4/t/lecture/ | |
33 | ) | |
34 | (?P<id>\d+) | |
35 | ''' | |
dcd4d95c S |
36 | _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1' |
37 | _ORIGIN_URL = 'https://www.udemy.com' | |
e5de3f6c S |
38 | _NETRC_MACHINE = 'udemy' |
39 | ||
6563837e | 40 | _TESTS = [{ |
e5de3f6c S |
41 | 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757', |
42 | 'md5': '98eda5b657e752cf945d8445e261b5c5', | |
43 | 'info_dict': { | |
44 | 'id': '160614', | |
45 | 'ext': 'mp4', | |
46 | 'title': 'Introduction and Installation', | |
47 | 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876', | |
48 | 'duration': 579.29, | |
49 | }, | |
50 | 'skip': 'Requires udemy account credentials', | |
5eb7db4e S |
51 | }, { |
52 | # new URL schema | |
53 | 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906', | |
54 | 'only_matching': True, | |
6563837e | 55 | }] |
e5de3f6c | 56 | |
ff9d5d09 | 57 | def _enroll_course(self, base_url, webpage, course_id): |
17b2d7ca S |
58 | checkout_url = unescapeHTML(self._search_regex( |
59 | r'href=(["\'])(?P<url>https?://(?:www\.)?udemy\.com/payment/checkout/.+?)\1', | |
60 | webpage, 'checkout url', group='url', default=None)) | |
61 | if checkout_url: | |
62 | raise ExtractorError( | |
f20756fb | 63 | 'Course %s is not free. You have to pay for it before you can download. ' |
17b2d7ca S |
64 | 'Use this URL to confirm purchase: %s' % (course_id, checkout_url), expected=True) |
65 | ||
66 | enroll_url = unescapeHTML(self._search_regex( | |
ff9d5d09 | 67 | r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1', |
17b2d7ca S |
68 | webpage, 'enroll url', group='url', default=None)) |
69 | if enroll_url: | |
ff9d5d09 S |
70 | if not enroll_url.startswith('http'): |
71 | enroll_url = compat_urlparse.urljoin(base_url, enroll_url) | |
17b2d7ca S |
72 | webpage = self._download_webpage(enroll_url, course_id, 'Enrolling in the course') |
73 | if '>You have enrolled in' in webpage: | |
74 | self.to_screen('%s: Successfully enrolled in the course' % course_id) | |
328f82d5 S |
75 | |
76 | def _download_lecture(self, course_id, lecture_id): | |
77 | return self._download_json( | |
78 | 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?%s' % ( | |
15707c7e | 79 | course_id, lecture_id, compat_urllib_parse_urlencode({ |
efcba804 | 80 | 'fields[lecture]': 'title,description,view_html,asset', |
328f82d5 | 81 | 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data', |
328f82d5 | 82 | })), |
24121bc7 | 83 | lecture_id, 'Downloading lecture JSON') |
328f82d5 | 84 | |
e5de3f6c S |
85 | def _handle_error(self, response): |
86 | if not isinstance(response, dict): | |
87 | return | |
88 | error = response.get('error') | |
89 | if error: | |
90 | error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message')) | |
91 | error_data = error.get('data') | |
92 | if error_data: | |
93 | error_str += ' - %s' % error_data.get('formErrors') | |
94 | raise ExtractorError(error_str, expected=True) | |
95 | ||
24121bc7 | 96 | def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata'): |
e2937118 S |
97 | headers = { |
98 | 'X-Udemy-Snail-Case': 'true', | |
99 | 'X-Requested-With': 'XMLHttpRequest', | |
100 | } | |
101 | for cookie in self._downloader.cookiejar: | |
102 | if cookie.name == 'client_id': | |
103 | headers['X-Udemy-Client-Id'] = cookie.value | |
104 | elif cookie.name == 'access_token': | |
105 | headers['X-Udemy-Bearer-Token'] = cookie.value | |
328f82d5 | 106 | headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value |
61c0663c S |
107 | |
108 | if isinstance(url_or_request, compat_urllib_request.Request): | |
109 | for header, value in headers.items(): | |
110 | url_or_request.add_header(header, value) | |
111 | else: | |
5c2266df | 112 | url_or_request = sanitized_Request(url_or_request, headers=headers) |
61c0663c | 113 | |
24121bc7 | 114 | response = super(UdemyIE, self)._download_json(url_or_request, video_id, note) |
61c0663c S |
115 | self._handle_error(response) |
116 | return response | |
e2937118 | 117 | |
e5de3f6c S |
118 | def _real_initialize(self): |
119 | self._login() | |
120 | ||
121 | def _login(self): | |
122 | (username, password) = self._get_login_info() | |
123 | if username is None: | |
78717fc3 | 124 | return |
e5de3f6c S |
125 | |
126 | login_popup = self._download_webpage( | |
dcd4d95c | 127 | self._LOGIN_URL, None, 'Downloading login popup') |
e5de3f6c | 128 | |
d609edf4 S |
129 | def is_logged(webpage): |
130 | return any(p in webpage for p in ['href="https://www.udemy.com/user/logout/', '>Logout<']) | |
131 | ||
132 | # already logged in | |
133 | if is_logged(login_popup): | |
e5de3f6c S |
134 | return |
135 | ||
dcd4d95c | 136 | login_form = self._form_hidden_inputs('login-form', login_popup) |
e5de3f6c | 137 | |
dcd4d95c | 138 | login_form.update({ |
dcd4d95c S |
139 | 'email': username.encode('utf-8'), |
140 | 'password': password.encode('utf-8'), | |
141 | }) | |
142 | ||
5c2266df | 143 | request = sanitized_Request( |
6e6bc8da | 144 | self._LOGIN_URL, urlencode_postdata(login_form)) |
dcd4d95c S |
145 | request.add_header('Referer', self._ORIGIN_URL) |
146 | request.add_header('Origin', self._ORIGIN_URL) | |
147 | ||
148 | response = self._download_webpage( | |
e2937118 | 149 | request, None, 'Logging in as %s' % username) |
e5de3f6c | 150 | |
d609edf4 | 151 | if not is_logged(response): |
dcd4d95c S |
152 | error = self._html_search_regex( |
153 | r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>', | |
154 | response, 'error message', default=None) | |
155 | if error: | |
156 | raise ExtractorError('Unable to login: %s' % error, expected=True) | |
e5de3f6c S |
157 | raise ExtractorError('Unable to log in') |
158 | ||
159 | def _real_extract(self, url): | |
810fb84d | 160 | lecture_id = self._match_id(url) |
e5de3f6c | 161 | |
328f82d5 S |
162 | webpage = self._download_webpage(url, lecture_id) |
163 | ||
164 | course_id = self._search_regex( | |
70cab344 | 165 | (r'data-course-id=["\'](\d+)', r'"id"\s*:\s*(\d+)'), |
a7ba57dc | 166 | webpage, 'course id') |
e5de3f6c | 167 | |
328f82d5 S |
168 | try: |
169 | lecture = self._download_lecture(course_id, lecture_id) | |
170 | except ExtractorError as e: | |
171 | # Error could possibly mean we are not enrolled in the course | |
172 | if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403: | |
ff9d5d09 | 173 | self._enroll_course(url, webpage, course_id) |
3092fc40 | 174 | lecture = self._download_lecture(course_id, lecture_id) |
328f82d5 S |
175 | else: |
176 | raise | |
177 | ||
178 | title = lecture['title'] | |
179 | description = lecture.get('description') | |
180 | ||
181 | asset = lecture['asset'] | |
182 | ||
183 | asset_type = asset.get('assetType') or asset.get('asset_type') | |
e2937118 S |
184 | if asset_type != 'Video': |
185 | raise ExtractorError( | |
186 | 'Lecture %s is not a video' % lecture_id, expected=True) | |
e5de3f6c | 187 | |
e2937118 | 188 | stream_url = asset.get('streamUrl') or asset.get('stream_url') |
328f82d5 S |
189 | if stream_url: |
190 | youtube_url = self._search_regex( | |
191 | r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None) | |
192 | if youtube_url: | |
193 | return self.url_result(youtube_url, 'Youtube') | |
e5de3f6c S |
194 | |
195 | video_id = asset['id'] | |
e2937118 | 196 | thumbnail = asset.get('thumbnailUrl') or asset.get('thumbnail_url') |
328f82d5 | 197 | duration = float_or_none(asset.get('data', {}).get('duration')) |
328f82d5 S |
198 | |
199 | formats = [] | |
f0e83681 S |
200 | |
201 | def extract_output_format(src): | |
202 | return { | |
203 | 'url': src['url'], | |
02d7634d | 204 | 'format_id': '%sp' % (src.get('height') or format_id), |
f0e83681 S |
205 | 'width': int_or_none(src.get('width')), |
206 | 'height': int_or_none(src.get('height')), | |
207 | 'vbr': int_or_none(src.get('video_bitrate_in_kbps')), | |
208 | 'vcodec': src.get('video_codec'), | |
209 | 'fps': int_or_none(src.get('frame_rate')), | |
210 | 'abr': int_or_none(src.get('audio_bitrate_in_kbps')), | |
211 | 'acodec': src.get('audio_codec'), | |
212 | 'asr': int_or_none(src.get('audio_sample_rate')), | |
213 | 'tbr': int_or_none(src.get('total_bitrate_in_kbps')), | |
214 | 'filesize': int_or_none(src.get('file_size_in_bytes')), | |
328f82d5 | 215 | } |
f0e83681 S |
216 | |
217 | outputs = asset.get('data', {}).get('outputs') | |
218 | if not isinstance(outputs, dict): | |
219 | outputs = {} | |
220 | ||
62f55aa6 S |
221 | def add_output_format_meta(f, key, format_id): |
222 | output = outputs.get(key) | |
223 | if isinstance(output, dict): | |
224 | output_format = extract_output_format(output) | |
225 | output_format.update(f) | |
226 | return output_format | |
227 | else: | |
228 | f['format_id'] = format_id | |
229 | return f | |
230 | ||
f0e83681 S |
231 | download_urls = asset.get('download_urls') |
232 | if isinstance(download_urls, dict): | |
233 | video = download_urls.get('Video') | |
234 | if isinstance(video, list): | |
235 | for format_ in video: | |
236 | video_url = format_.get('file') | |
237 | if not video_url: | |
238 | continue | |
239 | format_id = format_.get('label') | |
240 | f = { | |
241 | 'url': format_['file'], | |
242 | 'height': int_or_none(format_id), | |
243 | } | |
244 | if format_id: | |
245 | # Some videos contain additional metadata (e.g. | |
246 | # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208) | |
62f55aa6 | 247 | f = add_output_format_meta(f, format_id, '%sp' % format_id) |
f0e83681 | 248 | formats.append(f) |
3b35c342 | 249 | |
efcba804 S |
250 | view_html = lecture.get('view_html') |
251 | if view_html: | |
252 | view_html_urls = set() | |
253 | for source in re.findall(r'<source[^>]+>', view_html): | |
254 | attributes = extract_attributes(source) | |
255 | src = attributes.get('src') | |
256 | if not src: | |
257 | continue | |
258 | res = attributes.get('data-res') | |
259 | height = int_or_none(res) | |
260 | if src in view_html_urls: | |
261 | continue | |
262 | view_html_urls.add(src) | |
263 | if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8': | |
264 | m3u8_formats = self._extract_m3u8_formats( | |
265 | src, video_id, 'mp4', entry_protocol='m3u8_native', | |
266 | m3u8_id='hls', fatal=False) | |
267 | for f in m3u8_formats: | |
268 | m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url']) | |
269 | if m: | |
270 | if not f.get('height'): | |
271 | f['height'] = int(m.group('height')) | |
272 | if not f.get('tbr'): | |
273 | f['tbr'] = int(m.group('tbr')) | |
274 | formats.extend(m3u8_formats) | |
275 | else: | |
62f55aa6 | 276 | formats.append(add_output_format_meta({ |
efcba804 | 277 | 'url': src, |
efcba804 | 278 | 'height': height, |
62f55aa6 | 279 | }, res, '%dp' % height if height else None)) |
efcba804 | 280 | |
48dce58c | 281 | self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id')) |
e5de3f6c | 282 | |
e5de3f6c S |
283 | return { |
284 | 'id': video_id, | |
285 | 'title': title, | |
286 | 'description': description, | |
287 | 'thumbnail': thumbnail, | |
288 | 'duration': duration, | |
289 | 'formats': formats | |
290 | } | |
291 | ||
292 | ||
293 | class UdemyCourseIE(UdemyIE): | |
294 | IE_NAME = 'udemy:course' | |
328f82d5 | 295 | _VALID_URL = r'https?://www\.udemy\.com/(?P<id>[\da-z-]+)' |
6563837e | 296 | _TESTS = [] |
e5de3f6c S |
297 | |
298 | @classmethod | |
299 | def suitable(cls, url): | |
300 | return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url) | |
301 | ||
302 | def _real_extract(self, url): | |
328f82d5 S |
303 | course_path = self._match_id(url) |
304 | ||
305 | webpage = self._download_webpage(url, course_path) | |
e5de3f6c | 306 | |
61c0663c | 307 | response = self._download_json( |
e2937118 S |
308 | 'https://www.udemy.com/api-1.1/courses/%s' % course_path, |
309 | course_path, 'Downloading course JSON') | |
e5de3f6c | 310 | |
328f82d5 S |
311 | course_id = response['id'] |
312 | course_title = response.get('title') | |
e5de3f6c | 313 | |
ff9d5d09 | 314 | self._enroll_course(url, webpage, course_id) |
e5de3f6c | 315 | |
61c0663c | 316 | response = self._download_json( |
e2937118 S |
317 | 'https://www.udemy.com/api-1.1/courses/%s/curriculum' % course_id, |
318 | course_id, 'Downloading course curriculum') | |
e5de3f6c | 319 | |
4d402db5 | 320 | entries = [] |
5bafcf65 | 321 | chapter, chapter_number = None, None |
4d402db5 S |
322 | for asset in response: |
323 | asset_type = asset.get('assetType') or asset.get('asset_type') | |
324 | if asset_type == 'Video': | |
325 | asset_id = asset.get('id') | |
326 | if asset_id: | |
327 | entry = { | |
328 | '_type': 'url_transparent', | |
329 | 'url': 'https://www.udemy.com/%s/#/lecture/%s' % (course_path, asset['id']), | |
330 | 'ie_key': UdemyIE.ie_key(), | |
331 | } | |
5bafcf65 S |
332 | if chapter_number: |
333 | entry['chapter_number'] = chapter_number | |
4d402db5 S |
334 | if chapter: |
335 | entry['chapter'] = chapter | |
336 | entries.append(entry) | |
337 | elif asset.get('type') == 'chapter': | |
5bafcf65 | 338 | chapter_number = asset.get('index') or asset.get('object_index') |
4d402db5 | 339 | chapter = asset.get('title') |
e5de3f6c | 340 | |
5f6a1245 | 341 | return self.playlist_result(entries, course_id, course_title) |