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