1 from __future__ import unicode_literals
5 from .common import InfoExtractor
10 compat_urllib_request,
26 class UdemyIE(InfoExtractor):
33 lecture/view/?\?lectureId=|
34 [^/]+/learn/v4/t/lecture/
38 _LOGIN_URL = 'https://www.udemy.com/join/login-popup/?displayType=ajax&showSkipButton=1'
39 _ORIGIN_URL = 'https://www.udemy.com'
40 _NETRC_MACHINE = 'udemy'
43 'url': 'https://www.udemy.com/java-tutorial/#/lecture/172757',
44 'md5': '98eda5b657e752cf945d8445e261b5c5',
48 'title': 'Introduction and Installation',
49 'description': 'md5:c0d51f6f21ef4ec65f091055a5eef876',
52 'skip': 'Requires udemy account credentials',
55 'url': 'https://www.udemy.com/electric-bass-right-from-the-start/learn/v4/t/lecture/4580906',
56 'only_matching': True,
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,
62 # only outputs rendition
63 'url': 'https://www.udemy.com/how-you-can-help-your-local-community-5-amazing-examples/learn/v4/t/lecture/3225750?start=0',
64 'only_matching': True,
67 def _extract_course_info(self, webpage, video_id):
68 course = self._parse_json(
69 unescapeHTML(self._search_regex(
70 r'ng-init=["\'].*\bcourse=({.+?})[;"\']',
71 webpage, 'course', default='{}')),
72 video_id, fatal=False) or {}
73 course_id = course.get('id') or self._search_regex(
74 r'data-course-id=["\'](\d+)', webpage, 'course id')
75 return course_id, course.get('title')
77 def _enroll_course(self, base_url, webpage, course_id):
78 def combine_url(base_url, url):
79 return compat_urlparse.urljoin(base_url, url) if not url.startswith('http') else url
81 checkout_url = unescapeHTML(self._search_regex(
82 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/(?:payment|cart)/checkout/.+?)\1',
83 webpage, 'checkout url', group='url', default=None))
86 'Course %s is not free. You have to pay for it before you can download. '
87 'Use this URL to confirm purchase: %s'
88 % (course_id, combine_url(base_url, checkout_url)),
91 enroll_url = unescapeHTML(self._search_regex(
92 r'href=(["\'])(?P<url>(?:https?://(?:www\.)?udemy\.com)?/course/subscribe/.+?)\1',
93 webpage, 'enroll url', group='url', default=None))
95 webpage = self._download_webpage(
96 combine_url(base_url, enroll_url),
97 course_id, 'Enrolling in the course',
98 headers={'Referer': base_url})
99 if '>You have enrolled in' in webpage:
100 self.to_screen('%s: Successfully enrolled in the course' % course_id)
102 def _download_lecture(self, course_id, lecture_id):
103 return self._download_json(
104 'https://www.udemy.com/api-2.0/users/me/subscribed-courses/%s/lectures/%s?'
105 % (course_id, lecture_id),
106 lecture_id, 'Downloading lecture JSON', query={
107 'fields[lecture]': 'title,description,view_html,asset',
108 'fields[asset]': 'asset_type,stream_url,thumbnail_url,download_urls,stream_urls,data',
111 def _handle_error(self, response):
112 if not isinstance(response, dict):
114 error = response.get('error')
116 error_str = 'Udemy returned error #%s: %s' % (error.get('code'), error.get('message'))
117 error_data = error.get('data')
119 error_str += ' - %s' % error_data.get('formErrors')
120 raise ExtractorError(error_str, expected=True)
122 def _download_webpage_handle(self, *args, **kwargs):
123 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'
124 return super(UdemyIE, self)._download_webpage_handle(
125 *args, **compat_kwargs(kwargs))
127 def _download_json(self, url_or_request, *args, **kwargs):
129 'X-Udemy-Snail-Case': 'true',
130 'X-Requested-With': 'XMLHttpRequest',
132 for cookie in self._downloader.cookiejar:
133 if cookie.name == 'client_id':
134 headers['X-Udemy-Client-Id'] = cookie.value
135 elif cookie.name == 'access_token':
136 headers['X-Udemy-Bearer-Token'] = cookie.value
137 headers['X-Udemy-Authorization'] = 'Bearer %s' % cookie.value
139 if isinstance(url_or_request, compat_urllib_request.Request):
140 for header, value in headers.items():
141 url_or_request.add_header(header, value)
143 url_or_request = sanitized_Request(url_or_request, headers=headers)
145 response = super(UdemyIE, self)._download_json(url_or_request, *args, **kwargs)
146 self._handle_error(response)
149 def _real_initialize(self):
153 (username, password) = self._get_login_info()
157 login_popup = self._download_webpage(
158 self._LOGIN_URL, None, 'Downloading login popup')
160 def is_logged(webpage):
161 return any(re.search(p, webpage) for p in (
162 r'href=["\'](?:https://www\.udemy\.com)?/user/logout/',
166 if is_logged(login_popup):
169 login_form = self._form_hidden_inputs('login-form', login_popup)
173 'password': password,
176 response = self._download_webpage(
177 self._LOGIN_URL, None, 'Logging in',
178 data=urlencode_postdata(login_form),
180 'Referer': self._ORIGIN_URL,
181 'Origin': self._ORIGIN_URL,
184 if not is_logged(response):
185 error = self._html_search_regex(
186 r'(?s)<div[^>]+class="form-errors[^"]*">(.+?)</div>',
187 response, 'error message', default=None)
189 raise ExtractorError('Unable to login: %s' % error, expected=True)
190 raise ExtractorError('Unable to log in')
192 def _real_extract(self, url):
193 lecture_id = self._match_id(url)
195 webpage = self._download_webpage(url, lecture_id)
197 course_id, _ = self._extract_course_info(webpage, lecture_id)
200 lecture = self._download_lecture(course_id, lecture_id)
201 except ExtractorError as e:
202 # Error could possibly mean we are not enrolled in the course
203 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
204 self._enroll_course(url, webpage, course_id)
205 lecture = self._download_lecture(course_id, lecture_id)
209 title = lecture['title']
210 description = lecture.get('description')
212 asset = lecture['asset']
214 asset_type = asset.get('asset_type') or asset.get('assetType')
215 if asset_type != 'Video':
216 raise ExtractorError(
217 'Lecture %s is not a video' % lecture_id, expected=True)
219 stream_url = asset.get('stream_url') or asset.get('streamUrl')
221 youtube_url = self._search_regex(
222 r'(https?://www\.youtube\.com/watch\?v=.*)', stream_url, 'youtube URL', default=None)
224 return self.url_result(youtube_url, 'Youtube')
226 video_id = compat_str(asset['id'])
227 thumbnail = asset.get('thumbnail_url') or asset.get('thumbnailUrl')
228 duration = float_or_none(asset.get('data', {}).get('duration'))
231 automatic_captions = {}
235 def extract_output_format(src, f_id):
237 'url': src.get('url'),
238 'format_id': '%sp' % (src.get('height') or f_id),
239 'width': int_or_none(src.get('width')),
240 'height': int_or_none(src.get('height')),
241 'vbr': int_or_none(src.get('video_bitrate_in_kbps')),
242 'vcodec': src.get('video_codec'),
243 'fps': int_or_none(src.get('frame_rate')),
244 'abr': int_or_none(src.get('audio_bitrate_in_kbps')),
245 'acodec': src.get('audio_codec'),
246 'asr': int_or_none(src.get('audio_sample_rate')),
247 'tbr': int_or_none(src.get('total_bitrate_in_kbps')),
248 'filesize': int_or_none(src.get('file_size_in_bytes')),
251 outputs = asset.get('data', {}).get('outputs')
252 if not isinstance(outputs, dict):
255 def add_output_format_meta(f, key):
256 output = outputs.get(key)
257 if isinstance(output, dict):
258 output_format = extract_output_format(output, key)
259 output_format.update(f)
263 def extract_formats(source_list):
264 if not isinstance(source_list, list):
266 for source in source_list:
267 video_url = source.get('file') or source.get('src')
268 if not video_url or not isinstance(video_url, compat_str):
270 if source.get('type') == 'application/x-mpegURL' or determine_ext(video_url) == 'm3u8':
271 formats.extend(self._extract_m3u8_formats(
272 video_url, video_id, 'mp4', entry_protocol='m3u8_native',
273 m3u8_id='hls', fatal=False))
275 format_id = source.get('label')
278 'format_id': '%sp' % format_id,
279 'height': int_or_none(format_id),
282 # Some videos contain additional metadata (e.g.
283 # https://www.udemy.com/ios9-swift/learn/#/lecture/3383208)
284 f = add_output_format_meta(f, format_id)
287 def extract_subtitles(track_list):
288 if not isinstance(track_list, list):
290 for track in track_list:
291 if not isinstance(track, dict):
293 if track.get('kind') != 'captions':
295 src = track.get('src')
296 if not src or not isinstance(src, compat_str):
298 lang = track.get('language') or track.get(
299 'srclang') or track.get('label')
300 sub_dict = automatic_captions if track.get(
301 'autogenerated') is True else subtitles
302 sub_dict.setdefault(lang, []).append({
306 for url_kind in ('download', 'stream'):
307 urls = asset.get('%s_urls' % url_kind)
308 if isinstance(urls, dict):
309 extract_formats(urls.get('Video'))
311 view_html = lecture.get('view_html')
313 view_html_urls = set()
314 for source in re.findall(r'<source[^>]+>', view_html):
315 attributes = extract_attributes(source)
316 src = attributes.get('src')
319 res = attributes.get('data-res')
320 height = int_or_none(res)
321 if src in view_html_urls:
323 view_html_urls.add(src)
324 if attributes.get('type') == 'application/x-mpegURL' or determine_ext(src) == 'm3u8':
325 m3u8_formats = self._extract_m3u8_formats(
326 src, video_id, 'mp4', entry_protocol='m3u8_native',
327 m3u8_id='hls', fatal=False)
328 for f in m3u8_formats:
329 m = re.search(r'/hls_(?P<height>\d{3,4})_(?P<tbr>\d{2,})/', f['url'])
331 if not f.get('height'):
332 f['height'] = int(m.group('height'))
334 f['tbr'] = int(m.group('tbr'))
335 formats.extend(m3u8_formats)
337 formats.append(add_output_format_meta({
339 'format_id': '%dp' % height if height else None,
343 # react rendition since 2017.04.15 (see
344 # https://github.com/rg3/youtube-dl/issues/12744)
345 data = self._parse_json(
347 r'videojs-setup-data=(["\'])(?P<data>{.+?})\1', view_html,
348 'setup data', default='{}', group='data'), video_id,
349 transform_source=unescapeHTML, fatal=False)
350 if data and isinstance(data, dict):
351 extract_formats(data.get('sources'))
353 duration = int_or_none(data.get('duration'))
354 extract_subtitles(data.get('tracks'))
356 if not subtitles and not automatic_captions:
357 text_tracks = self._parse_json(
359 r'text-tracks=(["\'])(?P<data>\[.+?\])\1', view_html,
360 'text tracks', default='{}', group='data'), video_id,
361 transform_source=lambda s: js_to_json(unescapeHTML(s)),
363 extract_subtitles(text_tracks)
365 if not formats and outputs:
366 for format_id, output in outputs.items():
367 f = extract_output_format(output, format_id)
371 self._sort_formats(formats, field_preference=('height', 'width', 'tbr', 'format_id'))
376 'description': description,
377 'thumbnail': thumbnail,
378 'duration': duration,
380 'subtitles': subtitles,
381 'automatic_captions': automatic_captions,
385 class UdemyCourseIE(UdemyIE):
386 IE_NAME = 'udemy:course'
387 _VALID_URL = r'https?://(?:www\.)?udemy\.com/(?P<id>[^/?#&]+)'
391 def suitable(cls, url):
392 return False if UdemyIE.suitable(url) else super(UdemyCourseIE, cls).suitable(url)
394 def _real_extract(self, url):
395 course_path = self._match_id(url)
397 webpage = self._download_webpage(url, course_path)
399 course_id, title = self._extract_course_info(webpage, course_path)
401 self._enroll_course(url, webpage, course_id)
403 response = self._download_json(
404 'https://www.udemy.com/api-2.0/courses/%s/cached-subscriber-curriculum-items' % course_id,
405 course_id, 'Downloading course curriculum', query={
406 'fields[chapter]': 'title,object_index',
407 'fields[lecture]': 'title,asset',
412 chapter, chapter_number = [None] * 2
413 for entry in response['results']:
414 clazz = entry.get('_class')
415 if clazz == 'lecture':
416 asset = entry.get('asset')
417 if isinstance(asset, dict):
418 asset_type = asset.get('asset_type') or asset.get('assetType')
419 if asset_type != 'Video':
421 lecture_id = entry.get('id')
424 '_type': 'url_transparent',
425 'url': 'https://www.udemy.com/%s/learn/v4/t/lecture/%s' % (course_path, entry['id']),
426 'title': entry.get('title'),
427 'ie_key': UdemyIE.ie_key(),
430 entry['chapter_number'] = chapter_number
432 entry['chapter'] = chapter
433 entries.append(entry)
434 elif clazz == 'chapter':
435 chapter_number = entry.get('object_index')
436 chapter = entry.get('title')
438 return self.playlist_result(entries, course_id, title)