]>
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, |
0a439c5c | 8 | compat_str, |
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 | |
81da8cbc S |
57 | def _extract_course_info(self, webpage, video_id): |
58 | course = self._parse_json( | |
59 | unescapeHTML(self._search_regex( | |
60 | r'ng-init=["\'].*\bcourse=({.+?});', webpage, 'course', default='{}')), | |
61 | video_id, fatal=False) or {} | |
62 | course_id = course.get('id') or self._search_regex( | |
63 | (r'"id"\s*:\s*(\d+)', r'data-course-id=["\'](\d+)'), | |
64 | webpage, 'course id') | |
65 | return course_id, course.get('title') | |
66 | ||
ff9d5d09 | 67 | def _enroll_course(self, base_url, webpage, course_id): |
b24ab3e3 S |
68 | def combine_url(base_url, url): |
69 | return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url | |
70 | ||
17b2d7ca | 71 | checkout_url = unescapeHTML(self._search_regex( |
b24ab3e3 | 72 | r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/payment/checkout/.+?)\1', |
17b2d7ca S |
73 | webpage, 'checkout url', group='url', default=None)) |
74 | if checkout_url: | |
75 | raise ExtractorError( | |
f20756fb | 76 | 'Course %s is not free. You have to pay for it before you can download. ' |
b24ab3e3 S |
77 | 'Use this URL to confirm purchase: %s' |
78 | % (course_id, combine_url(base_url, checkout_url)), | |
79 | expected=True) | |
17b2d7ca S |
80 | |
81 | enroll_url = unescapeHTML(self._search_regex( | |
ff9d5d09 | 82 | r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1', |
17b2d7ca S |
83 | webpage, 'enroll url', group='url', default=None)) |
84 | if enroll_url: | |
b24ab3e3 S |
85 | webpage = self._download_webpage( |
86 | combine_url(base_url, enroll_url), | |
aabdc83d S |
87 | course_id, 'Enrolling in the course', |
88 | headers={'Referer': base_url}) | |
17b2d7ca S |
89 | if '>You have enrolled in' in webpage: |
90 | self.to_screen('%s: Successfully enrolled in the course' % course_id) | |
328f82d5 S |
91 | |
92 | def _download_lecture(self, course_id, lecture_id): | |
93 | return self._download_json( | |
75b81df3 S |
94 | 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?' |
95 | % (course_id, lecture_id), | |
96 | lecture_id, 'Downloading lecture JSON', query={ | |
97 | 'fields[lecture]': 'title,description,view_html,asset', | |
98 | 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,data', | |
99 | }) | |
328f82d5 | 100 | |
e5de3f6c S |
101 | def _handle_error(self, response): |
102 | if not isinstance(response, dict): | |
103 | return | |
104 | error = response.get('error') | |
105 | if error: | |
106 | error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message')) | |
107 | error_data = error.get('data') | |
108 | if error_data: | |
109 | error_str += ' - %s' % error_data.get('formErrors') | |
110 | raise ExtractorError(error_str, expected=True) | |
111 | ||
81da8cbc | 112 | def _download_json(self, url_or_request, *args, **kwargs): |
e2937118 S |
113 | headers = { |
114 | 'X-Udemy-Snail-Case': 'true', | |
115 | 'X-Requested-With': 'XMLHttpRequest', | |
116 | } | |
117 | for cookie in self._downloader.cookiejar: | |
118 | if cookie.name == 'client_id': | |
119 | headers['X-Udemy-Client-Id'] = cookie.value | |
120 | elif cookie.name == 'access_token': | |
121 | headers['X-Udemy-Bearer-Token'] = cookie.value | |
328f82d5 | 122 | headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value |
61c0663c S |
123 | |
124 | if isinstance(url_or_request, compat_urllib_request.Request): | |
125 | for header, value in headers.items(): | |
126 | url_or_request.add_header(header, value) | |
127 | else: | |
5c2266df | 128 | url_or_request = sanitized_Request(url_or_request, headers=headers) |
61c0663c | 129 | |
81da8cbc | 130 | response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs) |
61c0663c S |
131 | self._handle_error(response) |
132 | return response | |
e2937118 | 133 | |
e5de3f6c S |
134 | def _real_initialize(self): |
135 | self._login() | |
136 | ||
137 | def _login(self): | |
138 | (username, password) = self._get_login_info() | |
139 | if username is None: | |
78717fc3 | 140 | return |
e5de3f6c S |
141 | |
142 | login_popup = self._download_webpage( | |
dcd4d95c | 143 | self._LOGIN_URL, None, 'Downloading login popup') |
e5de3f6c | 144 | |
d609edf4 | 145 | def is_logged(webpage): |
807cf7b0 S |
146 | return any(re.search(p, webpage) for p in ( |
147 | r'href=["\'](?:https://www\.udemy\.com)?/user/logout/', | |
148 | r'>Logout<')) | |
d609edf4 S |
149 | |
150 | # already logged in | |
151 | if is_logged(login_popup): | |
e5de3f6c S |
152 | return |
153 | ||
dcd4d95c | 154 | login_form = self._form_hidden_inputs('login-form', login_popup) |
e5de3f6c | 155 | |
dcd4d95c | 156 | login_form.update({ |
a3373823 S |
157 | 'email': username, |
158 | 'password': password, | |
dcd4d95c S |
159 | }) |
160 | ||
dcd4d95c | 161 | response = self._download_webpage( |
75b81df3 S |
162 | self._LOGIN_URL, None, 'Logging in as %s' % username, |
163 | data=urlencode_postdata(login_form), | |
164 | headers={ | |
165 | 'Referer': self._ORIGIN_URL, | |
166 | 'Origin': self._ORIGIN_URL, | |
167 | }) | |
e5de3f6c | 168 | |
d609edf4 | 169 | if not is_logged(response): |
dcd4d95c S |
170 | error = self._html_search_regex( |
171 | r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>', | |
172 | response, 'error message', default=None) | |
173 | if error: | |
174 | raise ExtractorError('Unable to login: %s' % error, expected=True) | |
e5de3f6c S |
175 | raise ExtractorError('Unable to log in') |
176 | ||
177 | def _real_extract(self, url): | |
810fb84d | 178 | lecture_id = self._match_id(url) |
e5de3f6c | 179 | |
328f82d5 S |
180 | webpage = self._download_webpage(url, lecture_id) |
181 | ||
81da8cbc | 182 | course_id, _ = self._extract_course_info(webpage, lecture_id) |
e5de3f6c | 183 | |
328f82d5 S |
184 | try: |
185 | lecture = self._download_lecture(course_id, lecture_id) | |
186 | except ExtractorError as e: | |
187 | # Error could possibly mean we are not enrolled in the course | |
188 | if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403: | |
ff9d5d09 | 189 | self._enroll_course(url, webpage, course_id) |
3092fc40 | 190 | lecture = self._download_lecture(course_id, lecture_id) |
328f82d5 S |
191 | else: |
192 | raise | |
193 | ||
194 | title = lecture['title'] | |
195 | description = lecture.get('description') | |
196 | ||
197 | asset = lecture['asset'] | |
198 | ||
03caa463 | 199 | asset_type = asset.get('asset_type') or asset.get('assetType') |
e2937118 S |
200 | if asset_type != 'Video': |
201 | raise ExtractorError( | |
202 | 'Lecture %s is not a video' % lecture_id, expected=True) | |
e5de3f6c | 203 | |
03caa463 | 204 | stream_url = asset.get('stream_url') or asset.get('streamUrl') |
328f82d5 S |
205 | if stream_url: |
206 | youtube_url = self._search_regex( | |
207 | r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None) | |
208 | if youtube_url: | |
209 | return self.url_result(youtube_url, 'Youtube') | |
e5de3f6c | 210 | |
0a439c5c | 211 | video_id = compat_str(asset['id']) |
03caa463 | 212 | thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl') |
328f82d5 | 213 | duration = float_or_none(asset.get('data', {}).get('duration')) |
328f82d5 S |
214 | |
215 | formats = [] | |
f0e83681 S |
216 | |
217 | def extract_output_format(src): | |
218 | return { | |
219 | 'url': src['url'], | |
02d7634d | 220 | 'format_id': '%sp' % (src.get('height') or format_id), |
f0e83681 S |
221 | 'width': int_or_none(src.get('width')), |
222 | 'height': int_or_none(src.get('height')), | |
223 | 'vbr': int_or_none(src.get('video_bitrate_in_kbps')), | |
224 | 'vcodec': src.get('video_codec'), | |
225 | 'fps': int_or_none(src.get('frame_rate')), | |
226 | 'abr': int_or_none(src.get('audio_bitrate_in_kbps')), | |
227 | 'acodec': src.get('audio_codec'), | |
228 | 'asr': int_or_none(src.get('audio_sample_rate')), | |
229 | 'tbr': int_or_none(src.get('total_bitrate_in_kbps')), | |
230 | 'filesize': int_or_none(src.get('file_size_in_bytes')), | |
328f82d5 | 231 | } |
f0e83681 S |
232 | |
233 | outputs = asset.get('data', {}).get('outputs') | |
234 | if not isinstance(outputs, dict): | |
235 | outputs = {} | |
236 | ||
af4116f4 | 237 | def add_output_format_meta(f, key): |
62f55aa6 S |
238 | output = outputs.get(key) |
239 | if isinstance(output, dict): | |
240 | output_format = extract_output_format(output) | |
241 | output_format.update(f) | |
242 | return output_format | |
af4116f4 | 243 | return f |
62f55aa6 | 244 | |
f0e83681 S |
245 | download_urls = asset.get('download_urls') |
246 | if isinstance(download_urls, dict): | |
247 | video = download_urls.get('Video') | |
248 | if isinstance(video, list): | |
249 | for format_ in video: | |
250 | video_url = format_.get('file') | |
251 | if not video_url: | |
252 | continue | |
253 | format_id = format_.get('label') | |
254 | f = { | |
255 | 'url': format_['file'], | |
af4116f4 | 256 | 'format_id': '%sp' % format_id, |
f0e83681 S |
257 | 'height': int_or_none(format_id), |
258 | } | |
259 | if format_id: | |
260 | # Some videos contain additional metadata (e.g. | |
261 | # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208) | |
af4116f4 | 262 | f = add_output_format_meta(f, format_id) |
f0e83681 | 263 | formats.append(f) |
3b35c342 | 264 | |
efcba804 S |
265 | view_html = lecture.get('view_html') |
266 | if view_html: | |
267 | view_html_urls = set() | |
268 | for source in re.findall(r'<source[^>]+>', view_html): | |
269 | attributes = extract_attributes(source) | |
270 | src = attributes.get('src') | |
271 | if not src: | |
272 | continue | |
273 | res = attributes.get('data-res') | |
274 | height = int_or_none(res) | |
275 | if src in view_html_urls: | |
276 | continue | |
277 | view_html_urls.add(src) | |
278 | if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8': | |
279 | m3u8_formats = self._extract_m3u8_formats( | |
280 | src, video_id, 'mp4', entry_protocol='m3u8_native', | |
281 | m3u8_id='hls', fatal=False) | |
282 | for f in m3u8_formats: | |
283 | m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url']) | |
284 | if m: | |
285 | if not f.get('height'): | |
286 | f['height'] = int(m.group('height')) | |
287 | if not f.get('tbr'): | |
288 | f['tbr'] = int(m.group('tbr')) | |
289 | formats.extend(m3u8_formats) | |
290 | else: | |
62f55aa6 | 291 | formats.append(add_output_format_meta({ |
efcba804 | 292 | 'url': src, |
af4116f4 | 293 | 'format_id': '%dp' % height if height else None, |
efcba804 | 294 | 'height': height, |
af4116f4 | 295 | }, res)) |
efcba804 | 296 | |
48dce58c | 297 | self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id')) |
e5de3f6c | 298 | |
e5de3f6c S |
299 | return { |
300 | 'id': video_id, | |
301 | 'title': title, | |
302 | 'description': description, | |
303 | 'thumbnail': thumbnail, | |
304 | 'duration': duration, | |
305 | 'formats': formats | |
306 | } | |
307 | ||
308 | ||
309 | class UdemyCourseIE(UdemyIE): | |
310 | IE_NAME = 'udemy:course' | |
92519402 | 311 | _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)' |
6563837e | 312 | _TESTS = [] |
e5de3f6c S |
313 | |
314 | @classmethod | |
315 | def suitable(cls, url): | |
316 | return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url) | |
317 | ||
318 | def _real_extract(self, url): | |
328f82d5 S |
319 | course_path = self._match_id(url) |
320 | ||
321 | webpage = self._download_webpage(url, course_path) | |
e5de3f6c | 322 | |
81da8cbc | 323 | course_id, title = self._extract_course_info(webpage, course_path) |
e5de3f6c | 324 | |
ff9d5d09 | 325 | self._enroll_course(url, webpage, course_id) |
e5de3f6c | 326 | |
6bb46007 | 327 | response = self._download_json( |
81da8cbc | 328 | 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id, |
6bb46007 | 329 | course_id, 'Downloading course curriculum', query={ |
81da8cbc | 330 | 'fields[chapter]': 'title,object_index', |
03caa463 | 331 | 'fields[lecture]': 'title,asset', |
81da8cbc S |
332 | 'page_size': '1000', |
333 | }) | |
334 | ||
4d402db5 | 335 | entries = [] |
81da8cbc S |
336 | chapter, chapter_number = [None] * 2 |
337 | for entry in response['results']: | |
338 | clazz = entry.get('_class') | |
339 | if clazz == 'lecture': | |
03caa463 S |
340 | asset = entry.get('asset') |
341 | if isinstance(asset, dict): | |
342 | asset_type = asset.get('asset_type') or asset.get('assetType') | |
343 | if asset_type != 'Video': | |
344 | continue | |
81da8cbc S |
345 | lecture_id = entry.get('id') |
346 | if lecture_id: | |
4d402db5 S |
347 | entry = { |
348 | '_type': 'url_transparent', | |
b53a06e3 | 349 | 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']), |
81da8cbc | 350 | 'title': entry.get('title'), |
4d402db5 S |
351 | 'ie_key': UdemyIE.ie_key(), |
352 | } | |
5bafcf65 S |
353 | if chapter_number: |
354 | entry['chapter_number'] = chapter_number | |
4d402db5 S |
355 | if chapter: |
356 | entry['chapter'] = chapter | |
357 | entries.append(entry) | |
81da8cbc S |
358 | elif clazz == 'chapter': |
359 | chapter_number = entry.get('object_index') | |
360 | chapter = entry.get('title') | |
e5de3f6c | 361 | |
81da8cbc | 362 | return self.playlist_result(entries, course_id, title) |