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