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