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