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