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