]>
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, |
abe8766c | 8 | compat_kwargs, |
0a439c5c | 9 | compat_str, |
e5de3f6c | 10 | compat_urllib_request, |
ff9d5d09 | 11 | compat_urlparse, |
1cc79574 PH |
12 | ) |
13 | from ..utils import ( | |
efcba804 S |
14 | determine_ext, |
15 | extract_attributes, | |
e5de3f6c | 16 | ExtractorError, |
328f82d5 | 17 | float_or_none, |
3b35c342 | 18 | int_or_none, |
57a38a38 | 19 | js_to_json, |
5c2266df | 20 | sanitized_Request, |
2fbd8635 | 21 | try_get, |
17b2d7ca | 22 | unescapeHTML, |
6e6bc8da | 23 | urlencode_postdata, |
e5de3f6c S |
24 | ) |
25 | ||
26 | ||
27 | class UdemyIE(InfoExtractor): | |
28 | IE_NAME = 'udemy' | |
5eb7db4e S |
29 | _VALID_URL = r'''(?x) |
30 | https?:// | |
31 | www\.udemy\.com/ | |
32 | (?: | |
33 | [^#]+\#/lecture/| | |
34 | lecture/view/?\?lectureId=| | |
35 | [^/]+/learn/v4/t/lecture/ | |
36 | ) | |
37 | (?P<id>\d+) | |
38 | ''' | |
dcd4d95c S |
39 | _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1' |
40 | _ORIGIN_URL = 'https://www.udemy.com' | |
e5de3f6c S |
41 | _NETRC_MACHINE = 'udemy' |
42 | ||
6563837e | 43 | _TESTS = [{ |
e5de3f6c S |
44 | 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757', |
45 | 'md5': '98eda5b657e752cf945d8445e261b5c5', | |
46 | 'info_dict': { | |
47 | 'id': '160614', | |
48 | 'ext': 'mp4', | |
49 | 'title': 'Introduction and Installation', | |
50 | 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876', | |
51 | 'duration': 579.29, | |
52 | }, | |
53 | 'skip': 'Requires udemy account credentials', | |
5eb7db4e S |
54 | }, { |
55 | # new URL schema | |
56 | 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906', | |
57 | 'only_matching': True, | |
b7f87493 S |
58 | }, { |
59 | # no url in outputs format entry | |
60 | 'url': 'https://www.udemy.com/learn-web-development-complete-step-by-step-guide-to-success/learn/v4/t/lecture/4125812', | |
61 | 'only_matching': True, | |
85139634 S |
62 | }, { |
63 | # only outputs rendition | |
64 | 'url': 'https://www.udemy.com/how-you-can-help-your-local-community-5-amazing-examples/learn/v4/t/lecture/3225750?start=0', | |
65 | 'only_matching': True, | |
6563837e | 66 | }] |
e5de3f6c | 67 | |
81da8cbc S |
68 | def _extract_course_info(self, webpage, video_id): |
69 | course = self._parse_json( | |
70 | unescapeHTML(self._search_regex( | |
6f1ec339 S |
71 | r'ng-init=["\'].*\bcourse=({.+?})[;"\']', |
72 | webpage, 'course', default='{}')), | |
81da8cbc S |
73 | video_id, fatal=False) or {} |
74 | course_id = course.get('id') or self._search_regex( | |
6f1ec339 | 75 | r'data-course-id=["\'](\d+)', webpage, 'course id') |
81da8cbc S |
76 | return course_id, course.get('title') |
77 | ||
ff9d5d09 | 78 | def _enroll_course(self, base_url, webpage, course_id): |
b24ab3e3 S |
79 | def combine_url(base_url, url): |
80 | return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url | |
81 | ||
17b2d7ca | 82 | checkout_url = unescapeHTML(self._search_regex( |
5f5c7b92 | 83 | r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1', |
17b2d7ca S |
84 | webpage, 'checkout url', group='url', default=None)) |
85 | if checkout_url: | |
86 | raise ExtractorError( | |
f20756fb | 87 | 'Course %s is not free. You have to pay for it before you can download. ' |
b24ab3e3 S |
88 | 'Use this URL to confirm purchase: %s' |
89 | % (course_id, combine_url(base_url, checkout_url)), | |
90 | expected=True) | |
17b2d7ca S |
91 | |
92 | enroll_url = unescapeHTML(self._search_regex( | |
ff9d5d09 | 93 | r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1', |
17b2d7ca S |
94 | webpage, 'enroll url', group='url', default=None)) |
95 | if enroll_url: | |
b24ab3e3 S |
96 | webpage = self._download_webpage( |
97 | combine_url(base_url, enroll_url), | |
aabdc83d S |
98 | course_id, 'Enrolling in the course', |
99 | headers={'Referer': base_url}) | |
17b2d7ca S |
100 | if '>You have enrolled in' in webpage: |
101 | self.to_screen('%s: Successfully enrolled in the course' % course_id) | |
328f82d5 S |
102 | |
103 | def _download_lecture(self, course_id, lecture_id): | |
104 | return self._download_json( | |
75b81df3 S |
105 | 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?' |
106 | % (course_id, lecture_id), | |
107 | lecture_id, 'Downloading lecture JSON', query={ | |
108 | 'fields[lecture]': 'title,description,view_html,asset', | |
2fbd8635 | 109 | 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,stream_urls,captions,data', |
75b81df3 | 110 | }) |
328f82d5 | 111 | |
e5de3f6c S |
112 | def _handle_error(self, response): |
113 | if not isinstance(response, dict): | |
114 | return | |
115 | error = response.get('error') | |
116 | if error: | |
117 | error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message')) | |
118 | error_data = error.get('data') | |
119 | if error_data: | |
120 | error_str += ' - %s' % error_data.get('formErrors') | |
121 | raise ExtractorError(error_str, expected=True) | |
122 | ||
e5eadfa8 | 123 | def _download_webpage_handle(self, *args, **kwargs): |
abe8766c | 124 | kwargs.setdefault('headers', {})['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4' |
e5eadfa8 | 125 | return super(UdemyIE, self)._download_webpage_handle( |
abe8766c S |
126 | *args, **compat_kwargs(kwargs)) |
127 | ||
81da8cbc | 128 | def _download_json(self, url_or_request, *args, **kwargs): |
e2937118 S |
129 | headers = { |
130 | 'X-Udemy-Snail-Case': 'true', | |
131 | 'X-Requested-With': 'XMLHttpRequest', | |
132 | } | |
133 | for cookie in self._downloader.cookiejar: | |
134 | if cookie.name == 'client_id': | |
135 | headers['X-Udemy-Client-Id'] = cookie.value | |
136 | elif cookie.name == 'access_token': | |
137 | headers['X-Udemy-Bearer-Token'] = cookie.value | |
328f82d5 | 138 | headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value |
61c0663c S |
139 | |
140 | if isinstance(url_or_request, compat_urllib_request.Request): | |
141 | for header, value in headers.items(): | |
142 | url_or_request.add_header(header, value) | |
143 | else: | |
5c2266df | 144 | url_or_request = sanitized_Request(url_or_request, headers=headers) |
61c0663c | 145 | |
81da8cbc | 146 | response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs) |
61c0663c S |
147 | self._handle_error(response) |
148 | return response | |
e2937118 | 149 | |
e5de3f6c S |
150 | def _real_initialize(self): |
151 | self._login() | |
152 | ||
153 | def _login(self): | |
68217024 | 154 | username, password = self._get_login_info() |
e5de3f6c | 155 | if username is None: |
78717fc3 | 156 | return |
e5de3f6c S |
157 | |
158 | login_popup = self._download_webpage( | |
dcd4d95c | 159 | self._LOGIN_URL, None, 'Downloading login popup') |
e5de3f6c | 160 | |
d609edf4 | 161 | def is_logged(webpage): |
807cf7b0 S |
162 | return any(re.search(p, webpage) for p in ( |
163 | r'href=["\'](?:https://www\.udemy\.com)?/user/logout/', | |
164 | r'>Logout<')) | |
d609edf4 S |
165 | |
166 | # already logged in | |
167 | if is_logged(login_popup): | |
e5de3f6c S |
168 | return |
169 | ||
dcd4d95c | 170 | login_form = self._form_hidden_inputs('login-form', login_popup) |
e5de3f6c | 171 | |
dcd4d95c | 172 | login_form.update({ |
a3373823 S |
173 | 'email': username, |
174 | 'password': password, | |
dcd4d95c S |
175 | }) |
176 | ||
dcd4d95c | 177 | response = self._download_webpage( |
e4d95865 | 178 | self._LOGIN_URL, None, 'Logging in', |
75b81df3 S |
179 | data=urlencode_postdata(login_form), |
180 | headers={ | |
181 | 'Referer': self._ORIGIN_URL, | |
182 | 'Origin': self._ORIGIN_URL, | |
183 | }) | |
e5de3f6c | 184 | |
d609edf4 | 185 | if not is_logged(response): |
dcd4d95c S |
186 | error = self._html_search_regex( |
187 | r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>', | |
188 | response, 'error message', default=None) | |
189 | if error: | |
190 | raise ExtractorError('Unable to login: %s' % error, expected=True) | |
e5de3f6c S |
191 | raise ExtractorError('Unable to log in') |
192 | ||
193 | def _real_extract(self, url): | |
810fb84d | 194 | lecture_id = self._match_id(url) |
e5de3f6c | 195 | |
328f82d5 S |
196 | webpage = self._download_webpage(url, lecture_id) |
197 | ||
81da8cbc | 198 | course_id, _ = self._extract_course_info(webpage, lecture_id) |
e5de3f6c | 199 | |
328f82d5 S |
200 | try: |
201 | lecture = self._download_lecture(course_id, lecture_id) | |
202 | except ExtractorError as e: | |
203 | # Error could possibly mean we are not enrolled in the course | |
204 | if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403: | |
ff9d5d09 | 205 | self._enroll_course(url, webpage, course_id) |
3092fc40 | 206 | lecture = self._download_lecture(course_id, lecture_id) |
328f82d5 S |
207 | else: |
208 | raise | |
209 | ||
210 | title = lecture['title'] | |
211 | description = lecture.get('description') | |
212 | ||
213 | asset = lecture['asset'] | |
214 | ||
03caa463 | 215 | asset_type = asset.get('asset_type') or asset.get('assetType') |
e2937118 S |
216 | if asset_type != 'Video': |
217 | raise ExtractorError( | |
218 | 'Lecture %s is not a video' % lecture_id, expected=True) | |
e5de3f6c | 219 | |
03caa463 | 220 | stream_url = asset.get('stream_url') or asset.get('streamUrl') |
328f82d5 S |
221 | if stream_url: |
222 | youtube_url = self._search_regex( | |
223 | r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None) | |
224 | if youtube_url: | |
225 | return self.url_result(youtube_url, 'Youtube') | |
e5de3f6c | 226 | |
0a439c5c | 227 | video_id = compat_str(asset['id']) |
03caa463 | 228 | thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl') |
328f82d5 | 229 | duration = float_or_none(asset.get('data', {}).get('duration')) |
328f82d5 | 230 | |
3dfceb28 S |
231 | subtitles = {} |
232 | automatic_captions = {} | |
233 | ||
328f82d5 | 234 | formats = [] |
f0e83681 | 235 | |
3dfceb28 | 236 | def extract_output_format(src, f_id): |
f0e83681 | 237 | return { |
b7f87493 | 238 | 'url': src.get('url'), |
3dfceb28 | 239 | 'format_id': '%sp' % (src.get('height') or f_id), |
f0e83681 S |
240 | 'width': int_or_none(src.get('width')), |
241 | 'height': int_or_none(src.get('height')), | |
242 | 'vbr': int_or_none(src.get('video_bitrate_in_kbps')), | |
243 | 'vcodec': src.get('video_codec'), | |
244 | 'fps': int_or_none(src.get('frame_rate')), | |
245 | 'abr': int_or_none(src.get('audio_bitrate_in_kbps')), | |
246 | 'acodec': src.get('audio_codec'), | |
247 | 'asr': int_or_none(src.get('audio_sample_rate')), | |
248 | 'tbr': int_or_none(src.get('total_bitrate_in_kbps')), | |
249 | 'filesize': int_or_none(src.get('file_size_in_bytes')), | |
328f82d5 | 250 | } |
f0e83681 S |
251 | |
252 | outputs = asset.get('data', {}).get('outputs') | |
253 | if not isinstance(outputs, dict): | |
254 | outputs = {} | |
255 | ||
af4116f4 | 256 | def add_output_format_meta(f, key): |
62f55aa6 S |
257 | output = outputs.get(key) |
258 | if isinstance(output, dict): | |
3dfceb28 | 259 | output_format = extract_output_format(output, key) |
62f55aa6 S |
260 | output_format.update(f) |
261 | return output_format | |
af4116f4 | 262 | return f |
62f55aa6 | 263 | |
3dfceb28 S |
264 | def extract_formats(source_list): |
265 | if not isinstance(source_list, list): | |
266 | return | |
267 | for source in source_list: | |
268 | video_url = source.get('file') or source.get('src') | |
269 | if not video_url or not isinstance(video_url, compat_str): | |
270 | continue | |
913b61ee S |
271 | if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8': |
272 | formats.extend(self._extract_m3u8_formats( | |
273 | video_url, video_id, 'mp4', entry_protocol='m3u8_native', | |
274 | m3u8_id='hls', fatal=False)) | |
275 | continue | |
3dfceb28 S |
276 | format_id = source.get('label') |
277 | f = { | |
278 | 'url': video_url, | |
279 | 'format_id': '%sp' % format_id, | |
280 | 'height': int_or_none(format_id), | |
281 | } | |
282 | if format_id: | |
283 | # Some videos contain additional metadata (e.g. | |
284 | # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208) | |
285 | f = add_output_format_meta(f, format_id) | |
286 | formats.append(f) | |
287 | ||
57a38a38 S |
288 | def extract_subtitles(track_list): |
289 | if not isinstance(track_list, list): | |
290 | return | |
291 | for track in track_list: | |
292 | if not isinstance(track, dict): | |
293 | continue | |
294 | if track.get('kind') != 'captions': | |
295 | continue | |
296 | src = track.get('src') | |
297 | if not src or not isinstance(src, compat_str): | |
298 | continue | |
299 | lang = track.get('language') or track.get( | |
300 | 'srclang') or track.get('label') | |
301 | sub_dict = automatic_captions if track.get( | |
302 | 'autogenerated') is True else subtitles | |
303 | sub_dict.setdefault(lang, []).append({ | |
304 | 'url': src, | |
305 | }) | |
306 | ||
0ce76801 S |
307 | for url_kind in ('download', 'stream'): |
308 | urls = asset.get('%s_urls' % url_kind) | |
309 | if isinstance(urls, dict): | |
310 | extract_formats(urls.get('Video')) | |
3b35c342 | 311 | |
2fbd8635 S |
312 | captions = asset.get('captions') |
313 | if isinstance(captions, list): | |
314 | for cc in captions: | |
315 | if not isinstance(cc, dict): | |
316 | continue | |
317 | cc_url = cc.get('url') | |
318 | if not cc_url or not isinstance(cc_url, compat_str): | |
319 | continue | |
320 | lang = try_get(cc, lambda x: x['locale']['locale'], compat_str) | |
321 | sub_dict = (automatic_captions if cc.get('source') == 'auto' | |
322 | else subtitles) | |
323 | sub_dict.setdefault(lang or 'en', []).append({ | |
324 | 'url': cc_url, | |
325 | }) | |
326 | ||
efcba804 S |
327 | view_html = lecture.get('view_html') |
328 | if view_html: | |
329 | view_html_urls = set() | |
330 | for source in re.findall(r'<source[^>]+>', view_html): | |
331 | attributes = extract_attributes(source) | |
332 | src = attributes.get('src') | |
333 | if not src: | |
334 | continue | |
335 | res = attributes.get('data-res') | |
336 | height = int_or_none(res) | |
337 | if src in view_html_urls: | |
338 | continue | |
339 | view_html_urls.add(src) | |
340 | if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8': | |
341 | m3u8_formats = self._extract_m3u8_formats( | |
342 | src, video_id, 'mp4', entry_protocol='m3u8_native', | |
343 | m3u8_id='hls', fatal=False) | |
344 | for f in m3u8_formats: | |
345 | m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url']) | |
346 | if m: | |
347 | if not f.get('height'): | |
348 | f['height'] = int(m.group('height')) | |
349 | if not f.get('tbr'): | |
350 | f['tbr'] = int(m.group('tbr')) | |
351 | formats.extend(m3u8_formats) | |
352 | else: | |
62f55aa6 | 353 | formats.append(add_output_format_meta({ |
efcba804 | 354 | 'url': src, |
af4116f4 | 355 | 'format_id': '%dp' % height if height else None, |
efcba804 | 356 | 'height': height, |
af4116f4 | 357 | }, res)) |
efcba804 | 358 | |
3dfceb28 S |
359 | # react rendition since 2017.04.15 (see |
360 | # https://github.com/rg3/youtube-dl/issues/12744) | |
361 | data = self._parse_json( | |
362 | self._search_regex( | |
363 | r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html, | |
364 | 'setup data', default='{}', group='data'), video_id, | |
365 | transform_source=unescapeHTML, fatal=False) | |
366 | if data and isinstance(data, dict): | |
367 | extract_formats(data.get('sources')) | |
368 | if not duration: | |
369 | duration = int_or_none(data.get('duration')) | |
57a38a38 S |
370 | extract_subtitles(data.get('tracks')) |
371 | ||
372 | if not subtitles and not automatic_captions: | |
373 | text_tracks = self._parse_json( | |
374 | self._search_regex( | |
375 | r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html, | |
376 | 'text tracks', default='{}', group='data'), video_id, | |
377 | transform_source=lambda s: js_to_json(unescapeHTML(s)), | |
378 | fatal=False) | |
379 | extract_subtitles(text_tracks) | |
3dfceb28 | 380 | |
85139634 S |
381 | if not formats and outputs: |
382 | for format_id, output in outputs.items(): | |
383 | f = extract_output_format(output, format_id) | |
384 | if f.get('url'): | |
385 | formats.append(f) | |
386 | ||
48dce58c | 387 | self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id')) |
e5de3f6c | 388 | |
e5de3f6c S |
389 | return { |
390 | 'id': video_id, | |
391 | 'title': title, | |
392 | 'description': description, | |
393 | 'thumbnail': thumbnail, | |
394 | 'duration': duration, | |
3dfceb28 S |
395 | 'formats': formats, |
396 | 'subtitles': subtitles, | |
397 | 'automatic_captions': automatic_captions, | |
e5de3f6c S |
398 | } |
399 | ||
400 | ||
401 | class UdemyCourseIE(UdemyIE): | |
402 | IE_NAME = 'udemy:course' | |
92519402 | 403 | _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)' |
6563837e | 404 | _TESTS = [] |
e5de3f6c S |
405 | |
406 | @classmethod | |
407 | def suitable(cls, url): | |
408 | return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url) | |
409 | ||
410 | def _real_extract(self, url): | |
328f82d5 S |
411 | course_path = self._match_id(url) |
412 | ||
413 | webpage = self._download_webpage(url, course_path) | |
e5de3f6c | 414 | |
81da8cbc | 415 | course_id, title = self._extract_course_info(webpage, course_path) |
e5de3f6c | 416 | |
ff9d5d09 | 417 | self._enroll_course(url, webpage, course_id) |
e5de3f6c | 418 | |
6bb46007 | 419 | response = self._download_json( |
81da8cbc | 420 | 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id, |
6bb46007 | 421 | course_id, 'Downloading course curriculum', query={ |
81da8cbc | 422 | 'fields[chapter]': 'title,object_index', |
03caa463 | 423 | 'fields[lecture]': 'title,asset', |
81da8cbc S |
424 | 'page_size': '1000', |
425 | }) | |
426 | ||
4d402db5 | 427 | entries = [] |
81da8cbc S |
428 | chapter, chapter_number = [None] * 2 |
429 | for entry in response['results']: | |
430 | clazz = entry.get('_class') | |
431 | if clazz == 'lecture': | |
03caa463 S |
432 | asset = entry.get('asset') |
433 | if isinstance(asset, dict): | |
434 | asset_type = asset.get('asset_type') or asset.get('assetType') | |
435 | if asset_type != 'Video': | |
436 | continue | |
81da8cbc S |
437 | lecture_id = entry.get('id') |
438 | if lecture_id: | |
4d402db5 S |
439 | entry = { |
440 | '_type': 'url_transparent', | |
b53a06e3 | 441 | 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']), |
81da8cbc | 442 | 'title': entry.get('title'), |
4d402db5 S |
443 | 'ie_key': UdemyIE.ie_key(), |
444 | } | |
5bafcf65 S |
445 | if chapter_number: |
446 | entry['chapter_number'] = chapter_number | |
4d402db5 S |
447 | if chapter: |
448 | entry['chapter'] = chapter | |
449 | entries.append(entry) | |
81da8cbc S |
450 | elif clazz == 'chapter': |
451 | chapter_number = entry.get('object_index') | |
452 | chapter = entry.get('title') | |
e5de3f6c | 453 | |
81da8cbc | 454 | return self.playlist_result(entries, course_id, title) |